Created
January 19, 2018 01:57
-
-
Save milon/79aeb68d3153bc6811fe9e771138c3ed to your computer and use it in GitHub Desktop.
Binary Search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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