3.11 程序改错
问题:
二分查找的错误代码:
int bisearch(char** arr, int b, int e, char* v)
{
int minIndex = b, maxIndex = e, midIndex;
while(minIndex < maxIndex)
{
midIndex = (minIndex + maxIndex) / 2;
if (strcmp(arr[midIndex], v) <= 0)
{
minIndex = midIndex;
}
else
{
maxIndex = midIndex - 1;
}
}
if(!strcmp(arr[maxIndex], v))
{
return maxIndex;
}
else
{
return -1;
}
}
递归程序要注意三方面问题:初始条件、转化、终止条件。针对上面这个程序,我们考虑如下:
第一个问题:midIndex = (minIndex + maxIndex) / 2;
可能溢出,最好改成:midIndex = minIndex + (maxIndex - minIndex) / 2;
第二个问题:循环终止条件可能无法到达,比如minIndex = 2, maxIndex = 3, 而arr[minIndex] <= v的时候,程序将进入死循环。
修改后代码如下:
int bisearch(char** arr, int b, int e, char* v)
{
int minIndex = b, maxIndex = e, midIndex;
while(minIndex < maxIndex - 1)
{
midIndex = minIndex + (maxIndex - minIndex) / 2;
if (strcmp(arr[midIndex], v) <= 0)
{
minIndex = midIndex;
}
else
{
maxIndex = midIndex;
}
}
if(!strcmp(arr[maxIndex], v))
{
return maxIndex;
}
else if(!strcmp(arr[minIndex, v]))
{
return minIndex;
}
else
{
return -1;
}
}
浙公网安备 33010602011771号