Skip to content

Instantly share code, notes, and snippets.

@milon
Created January 19, 2018 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milon/79aeb68d3153bc6811fe9e771138c3ed to your computer and use it in GitHub Desktop.
Save milon/79aeb68d3153bc6811fe9e771138c3ed to your computer and use it in GitHub Desktop.
Binary Search
//Binary search
#include<iostream>
#include<algorithm>
using namespace std;
int binary_search(int a[], int size, int key) {
int beg = 0, end = size-1;
int mid = (beg+end)/2;
while(beg<=end){
if(key<a[mid])
end = mid-1;
else
beg = mid+1;
if(a[mid]==key)
break;
mid = (beg+end)/2;
}
if(a[mid]==key)
return mid+1;
return 0;
}
int main() {
int n, key;
cout<<"How many number do you want: ";
cin>>n;
int arr[n];
cout<<"Enter "<<n<<" numbers:"<<endl;
for(int i=0;i<n;i++)
cin>>arr[i];
sort(arr, arr+n);
cout<<"Sorted elements are:"<<endl;
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
cout<<"Enter the searching number: ";
cin>>key;
int res = binary_search(arr, n, key);
if(res==0)
cout<<"Key not found."<<endl;
else
cout<<"Key found at position "<<res<<"."<<endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment