源程序错误
int BinSearch(int *arr,int len,int key)
{
int low = 0;
int high = len-1;
int mid;
while(low < high)
{
mid = (low+high)>>1;//(low+high)/2
if(arr[mid] == key)
{
return mid;
}
else if(arr[mid] < key)//后半段查找
{
low = mid;
}
else
{
high = mid;
}
}
return -1;
}
int main()
{
int arr[] = {1,2,3,4,5,6,7,8,9,10};
for(int i=0;i<13;i++)
{
printf("%d\n",BinSearch(arr,10,i));
}
return 0;
}
调试分析:
(0+9)/2=4 5<9 mid=4 high=9
(4+9)/2=6 7<9 mid=6 high=9
(6+9)/2=7 8<9 mid=7 high=9
(7+9)/2=8 9<9(错误)
因函数进行循环时先运行arr[mid] == key,即比较过一次
所以else if 时
如果是low=mid时,所以应把后一个数组地址赋值给low
同样high=mid时,所以应把前一个数组地址赋值给high
1.while(low <high)-->改为 while(low <=high)
2.else if(arr[mid] < key)
{
low = mid;--> 改为low=mid+1;
}
else
{
high = mid;--> 改为high = mid-1;
}