1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#include <iostream>
int binarySearch(int * arr, int low, int high, int key) {
if(low > high)
return -1;
int mid=(low+high)/2;
if(arr[mid] == key)
return mid;
else if(arr[mid]<key) {
binarySearch(arr, mid+1, high, key);
}
else{
binarySearch(arr, low, mid-1, key);
}
}
int main() {
int arr[] = {1,3,5,7,8,9, 10, 11, 13};
std::cout << binarySearch(arr, 0, 8, 5) << std::endl;
std::cout << binarySearch(arr, 0, 8, 6) << std::endl;
std::cout << binarySearch(arr, 0, 8, 10) << std::endl;
return 0;
}
|