Skip to content

Instantly share code, notes, and snippets.

@na5imuzzaman
Last active September 24, 2017 22:07
Show Gist options
  • Save na5imuzzaman/42636d55c71ed1fad5445836e0b0baf1 to your computer and use it in GitHub Desktop.
Save na5imuzzaman/42636d55c71ed1fad5445836e0b0baf1 to your computer and use it in GitHub Desktop.
Binary_Search (Easy).cpp
/* Nasim */
#include<iostream>
#define re(n) for(int i=0;i<n;i++)
using namespace std;
int Bs(int arr[],int l,int r,int x)
{
int mid;
while(l<=r)
{
mid = l+(r-l)/2;
if (arr[mid] == x)
return mid;
else if (arr[mid] > x)
r = mid-1;
else
l = mid+1;
}
return -1;
}
int main()
{
int n;
cin>>n;
int arr[n];
re(n)
cin>>arr[i];
cout<<"Have to Find : ";
int x;
cin>>x;
int res = Bs(arr,0,n-1,x);
if(res == -1)
cout<<"Not Found\n";
else
cout<<"Found at position "<<res<<" <0-base indexing>\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment