Skip to content

Instantly share code, notes, and snippets.

@shonenada
Created December 12, 2012 11:25
Show Gist options
  • Save shonenada/4267080 to your computer and use it in GitHub Desktop.
Save shonenada/4267080 to your computer and use it in GitHub Desktop.
Binary Search Recursive
#include<iostream>
using namespace std;
int bs(int* a, int key, int low, int high){
int mid;
mid = (low+high) / 2 ;
if(low>high){
return -1;
}
if( key == a[mid]) {
return mid;
}
else if(key > a[mid]){
low = mid + 1;
bs(a, key, low, high);
}
else if ( key < a[mid]){
high = mid - 1;
bs(a, key, low ,high);
}
}
void sort(int* arr,int n){
int i,j,temp;
for(i=0;i<n;i++){
for(j=0;j<n-i-1;j++){
if (arr[j] > arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main(){
int arr[1000];
int i, key, n;
int result;
cin >> n;
for(i=0;i<n;i++)
cin >> arr[i];
cin >> key;
sort(arr, n);
result = bs(arr,key,0,n-1);
cout << result << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment