我想知道为什么我的二分查找返回的值与线性搜索不同。有人可以向我解释我做错了什么吗?我应该回来一些不同的东西吗?
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.
答案 0 :(得分:-1)
尝试将您的逻辑更改为:
int midIndex = (lowIndex + highIndex) / 2;
while (lowIndex <= highIndex) {
if ((words[midIndex]).equals(wordToFind)) { //use equals
return midIndex;
}
if (wordToFind.compareTo(words[midIndex]) > 0) { //wordToFind > midIndex
lowIndex = midIndex + 1;
}
if (wordToFind.compareTo(words[midIndex]) < 0) { //wordToFind < midIndex
highIndex = midIndex - 1;
}
// getting rid of infinite loop when the value is not in the list
if (lowIndex==highIndex && !wordToFind.compareTo(words[midIndex]) {
return -1;
}
midIndex = (lowIndex + highIndex) / 2; // notice removing lowindex++
}
lowIndex++
内的while
不是必需的,因为那是更新lowIndex而不管BS算法是否根据与midIndex值的比较更新索引。