【发布时间】:2016-11-16 05:52:46
【问题描述】:
我想知道为什么我的二分搜索返回的值与我的线性搜索不同。有人可以向我解释我做错了什么吗?我应该返回不同的东西吗?
public class BinarySearch extends SearchAlgorithm
{
public int search (String [] words, String wordToFind) throws ItemNotFoundException {
int lowIndex = 0;
int highIndex = words.length - 1;
while (lowIndex <= highIndex) {
int midIndex = (lowIndex + highIndex) / 2;
if ((words[midIndex]).equals(wordToFind)) {
return midIndex;
}
if (wordToFind.compareTo(words[midIndex]) > 0) { //wordToFind > midIndex
lowIndex = midIndex + 1;
}
if (wordToFind.compareTo(words[midIndex]) < 0) { //wordToFind < midIndex
highIndex = midIndex - 1;
}
lowIndex++;
}
return -1;
}
}
这是它返回的内容。第一组是线性搜索,第二组是二进制。
DISCIPLINES found at index: 11780 taking 0 comparisons.
TRANSURANIUM found at index: 43920 taking 0 comparisons.
HEURISTICALLY found at index: 18385 taking 0 comparisons.
FOO found at index: -1 taking 0 comparisons.
DISCIPLINES found at index: 11780 taking 0 comparisons.
TRANSURANIUM found at index: 43920 taking 0 comparisons.
HEURISTICALLY found at index: -1 taking 0 comparisons.
FOO found at index: -1 taking 0 comparisons.
【问题讨论】:
-
哪个是正确的?
-
words的内容是什么?您的线性搜索显示没有找到。 -
建议对字符串使用
.equals而不是==,数组也是排序的吗? -
上面那一项是正确的。 “FOO”不在单词列表中。线性搜索(顶部)正在返回它们的位置。它是一个充满文字的文本文件。
-
按字母顺序排列。