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
|
#include <iostream>
using namespace std;
int binsearch(int* a, int val, int lo, int hi) {
if (hi < lo) return -1;
int mid = (lo+hi)/2;
if (val < a[mid]) {
return binsearch(a, val, lo, mid-1);
} else if (val > a[mid]) {
return binsearch(a, val, mid+1, hi);
} else {
return lo;
}
}
int main(void) {
int a[10] = {0,1,2,3,4,5,6,7,8,9};
int lo = 0;
int hi = 9;
int val = 3;
cout << binsearch(a, val, lo, hi) << endl;
}
|