#include<iostream>
//date 2013.10.15
//reference http://blog.csdn.net/v_july_v/article/details/7093204
using namespace std;
int binary_search(int array[], int n, int value)
{
int left =0;
int right = n-1;
while (left <= right)
{
//防止溢出
int middle = left + ((right - left) >> 1);
if (array[middle] > value)
{
right = middle -1;
}
else if (array[middle] < value)
{
left = middle +1;
}
else
{
//放在后面减少比对次数
return middle;
}
}
return -1;
}
int main(int argc, char *argv[])
{
int array[6] = {1, 2, 4, 6, 8, 9};
int nreturn = binary_search(array, 6, 4);
cout<<nreturn<<endl;
return 0;
}
二分查找
最新推荐文章于 2022-02-16 14:31:27 发布