#include <iostream>
using namespace std;
int binarySearch(int arr[], int size, int key) {
int si = 0;
int ei = size-1;
while(si <= ei) {
int mid = si + (ei-si)/2;
if(arr[mid] == key) {
return mid;
}
else if(arr[mid] <= key) {
si = mid+1; // go to right half
} else {
ei = mid-1; // go to left half
}
}
return -1;
}
int main()
{
int arr[] = {1, 4, 6, 7};
int size = sizeof(arr)/sizeof(int);
cout << binarySearch(arr, size, 6);
return 0;
}
No comments:
Post a Comment