3.11 程序改错
2013-09-02 00:22
183 查看
问题:
二分查找的错误代码:
递归程序要注意三方面问题:初始条件、转化、终止条件。针对上面这个程序,我们考虑如下:
第一个问题: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) { 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; } }
相关文章推荐
- 编程之美:第三章 结构之法 3.11程序改错
- 3.11 程序改错(二分查找)
- 读书笔记之编程之美 - 3.11 程序改错
- 3.11 程序改错
- 编程之美,3.11程序改错, 二分扩展
- 二分查找 编程之美3.11 程序改错
- [编程之美] PSet3.11 程序改错:二分查找与扩展
- 程序改错
- 《编程之美》“程序改错”一文之我见
- 北化oj 2102 - 程序改错 - 二维数组参数传递
- 程序改错
- 全国计算机等级考试C语言考试程序改错题
- 6.3程序改错
- 2109 : 程序改错 - memory函数
- 第四周——程序改错
- 关于类程序改错
- 2013第六周上机任务【项目1 程序改错】
- 程序改错题
- C语言终极面试-----程序代码评价或改错
- 基于opencv的计算机视觉技术实现 第五章节第一个程序 改错