1 #include<iostream>
2 using namespace std;
3
4 //return the position of an lelment in a sorted array of
5 //size n with value K, If none exist, return -1
6 int binarySearch(int array[], int n , int K){
7 int l = -1;
8 int r = n;
9 while( l + 1 != r){//stop when l and r meet
10 int i = (l + r) / 2;
11 if( K < array[i]) r = i;
12 if( K > array[i]) l = i;
13 if( array[i] == K) return i;
14 }
15 return -1;
16 }
17
18 int main()
19 {
20 int array[] = {1,2,2,2,3,4,5,6};
21 cout<<binarySearch(array,8,3)<<endl;
22
23 system("pause");
24 return 0;
25 }
26
27