Created
December 12, 2012 11:25
-
-
Save shonenada/4267080 to your computer and use it in GitHub Desktop.
Binary Search Recursive
This file contains 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
#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