对于我的班级,我需要制作一个既使用二分搜索又使用线性搜索的程序.线性搜索工作正常,所以我知道问题不在于不存在所需的搜索词.
我试图找到答案,但这似乎是一个非常独特的问题.
我正在从文件中读取书籍列表并将其放入存储标题和ID号的自定义Books类中的数组中.我正在搜索身份证号码,每当身份证号码为奇数时,它就可以正常工作; 如果是偶数,则会产生无限循环.
这是有问题的代码.
private String binarySearch(String indexNumber){ int left, middle, right, compare; String book = null; Boolean found = false; left = 0; right = list.length -1; while (found == false) { middle = (left + right) / 2; compare = list[middle].index.compareTo(indexNumber); if (compare == 0) { book = list[middle].title; found = true; } else { if (compare > 0) { right = middle - 1; System.out.println("New Right: " + right); } else { left = middle + 1; System.out.println("New Left: " + left); } } } return book; }
编辑:修改代码
private String binarySearch(String indexNumber){ int left, middle, right, compare; String book = null; left = 0; right = list.length -1; while (left <= right) { middle = (left + right) / 2; compare = list[middle].index.compareTo(indexNumber); if (compare == 0) { book = list[middle].title.toString(); break; //tried a return here and same problem as described below } else { if (compare > 0) { right = middle - 1; } else { left = middle + 1; } } } return book; }
这修复了无限循环,但它仍然只返回循环之前的空书值(但仅在偶数上,奇数仍然正确显示),即使我将return语句放在当前中断的位置.
二进制搜索的问题在于它坚持找到匹配项; 否则,它根本不会退出.
要解决此问题,请将found == false
条件替换为left <= right
:
while (left <= right) { ... if (compare == 0) { book = list[middle].title; break; } ... }