Skip to content

Instantly share code, notes, and snippets.

@zainulhasan
Created August 3, 2015 05:19
Show Gist options
  • Save zainulhasan/c674c1fa822424e8e09e to your computer and use it in GitHub Desktop.
Save zainulhasan/c674c1fa822424e8e09e to your computer and use it in GitHub Desktop.
/******************************
binarySearch.cpp
Auther:Syed Zain Ul hasan
*****************************/
#include <iostream>
using namespace std;
int binary_search(int arr[],int n,int item){
int start=0;
int end=n;
int mid=(start+end)/2;
while(start<=end){
if(arr[mid]==item)
return mid;
else if (item>arr[mid])
start=mid+1;
else if (item<arr[mid])
end=mid-1;
mid=(start+end)/2;
}
return -1;
}
int main() {
int arr[10]={2,5,7,8,9,45,79,87,98,100};
int item=45;
int index=binary_search(arr,10,item);
if(index!=-1)
cout<<item<<" Found at location : "<<index;
else
cout<<item<<" Not Found ";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment