写二分的时候经常要测试好久边界问题。有人给出了一个一般使用的方法
http://blog.csdn.net/v_july_v/article/details/7093204
//right=n-1 => while(left <= right) => right=middle-1;
//right=n => while(left < right) => right=middle;
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; //right赋值,适时而变
}
else if(array[middle]<value)
{
left=middle+1;
}
else
return middle;
}
return -1;
}