code like this,in page 44.
int binsearch(int x, int v[], int n)
{
int low, high, mid;
low = 0;
high = n - 1;
while(low <= high){
mid = (high+low)/2;
if(x < v[mid]){
high = mid + 1;
}else if(x > v[mid]){
low = mid + 1;
}else{
return mid;
}
printf("mid is %d\n",mid);
}
return -1;
}
int main(void)
{
int v[] = {2,3,4,7,8,23,54,65,76};
int ret = binsearch(7, v, sizeof(v)/sizeof(int));
printf("%d,ret is %d\n", sizeof(v),ret);
return 0;
}
compile and run it,dead loop as a result! so the line “low = mid + 1;” should take as “low = mid;”, is that right?thx.
The problem in the code you posted is not the value of
low, but in the test for the setting of the value ofhigh… ifxis less thanv[mid], then the new index value ofhighshould be one less than, not greater thanmid. So you want to change the following:to:
You can see a working example here: http://ideone.com/E6Ma8