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