#include <iostream>
using namespace std;
int binarySearch(int a[],int n,int key)
{
int low,high,mid;
low = 0;
high = n-1;
while(low <= high) //记得这个等号...
{
mid = (low + high)/2;
if (key < a[mid])
high = mid - 1;
else if (key > a[mid])
low = mid + 1;
else
return mid;
}
}
int main(int argc, char const *argv[])
{
int a[] = {1,1,2,3,5,7,9};
int pos = binarySearch(a,sizeof(a)/sizeof(int),5);
cout << pos;
return 0;
}
来源:oschina
链接:https://my.oschina.net/u/857259/blog/86160