您的位置:首页 > 其它

3.11 程序改错

2013-09-02 00:22 183 查看
问题:

二分查找的错误代码:

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: