Binary Search

 

#include <bits/stdc++.h>
using namespace std ;

int binary_search(int a[],int n,int key){
int start{0};
int end{n-1};
while (start <= end){
int mid{(start + end)/2} ;
if (key == a[mid]){
return mid ;
}
else if (a[mid] > key){
end = mid - 1 ;
} else{
start = mid + 1 ;
}
}
return -1 ;

}

int main (){
int n ;
cin >> n ;
int a[n];
for (int i = 0; i < n; ++i) {
cin >> a[i];

}
cout << "enter key " << '\n' ;
int key ;
cin >> key ;
sort(a,a+n) ;
int position = binary_search(a,n,key) ;
if (position == -1) cout << "key not found " ;
else cout << "key found at " << position ;

return 0 ;
}

Comments

Popular posts from this blog

CodeChef::CSUB

How Recursion Works?

Atcoder Educational Dp contest :: C vacation