主题:这里的折半查找如何实现只进行一次测试?
int binsearch(int x,int v[],int n)
{
//printf("enter function!\n");
int low,high,mid;
low = 0;
high = n - 1;
while (low <= high){
mid = (low + high) / 2;
//printf("low = %d,high = %d,mid = %d\n",low,high,mid);
if (x < v[mid]) high = mid - 1;
else if (x > v[mid]) low = mid + 1;
else return mid;
}
return -1;
}
这是一段折半查找的代码,有一道题要求我将while循环内的两次测试改成一次(代价是在循环外做更多的测试),请问该如何做?
{
//printf("enter function!\n");
int low,high,mid;
low = 0;
high = n - 1;
while (low <= high){
mid = (low + high) / 2;
//printf("low = %d,high = %d,mid = %d\n",low,high,mid);
if (x < v[mid]) high = mid - 1;
else if (x > v[mid]) low = mid + 1;
else return mid;
}
return -1;
}
这是一段折半查找的代码,有一道题要求我将while循环内的两次测试改成一次(代价是在循环外做更多的测试),请问该如何做?