代码清单3-18(纠正错误后的二分查找源码)
int bisearch(char** arr, int b, int e, char* v)
{
int minIndex = b, maxIndex = e, midIndex;
// 循环结束有两种情况:
// 若minIndex为偶数则minIndex == maxIndex;
// 否则就是minIndex == maxIndex – 1
while(minIndex < maxIndex - 1)
{
midIndex = minIndex + (maxIndex - minIndex) / 2;
if(strcmp(arr[midIndex] , v) <= 0 )
{
minIndex = midIndex;
}
else
{
// 不需要midIndex – 1,防止minIndex == maxIndex
maxIndex = midIndex;
}
}
if(!strcmp(arr[maxIndex] , v)) // 先判断序号最大的值
{
return maxIndex;
}
else if (!strcmp(arr[minIndex] , v) )
{
return minIndex;
}
else
{
return -1;
}
}