Skip to content

Instantly share code, notes, and snippets.

@amankharwal
Created November 11, 2020 15:10
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 amankharwal/3fcdc596ec91de5f04776fea61d2a1ba to your computer and use it in GitHub Desktop.
Save amankharwal/3fcdc596ec91de5f04776fea61d2a1ba to your computer and use it in GitHub Desktop.
#include<iostream>
using namespace std;
int binarySearch(int arr[], int n, int key){
int s = 0;
int e = n;
while(s<=e){
int mid=(s+e)/2;
if (arr[mid]==key){
return mid;
}
else if(arr[mid]>key){
e=mid-1;
}
else{
s=mid+1;
}
}
return -1;
}
int main(){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
int key;
cin>>key;
cout<<binarySearch(arr, n, key)<<endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment