【问题标题】:Binary search for an array of strings二分查找字符串数组
【发布时间】: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”不在单词列表中。线性搜索(顶部)正在返回它们的位置。它是一个充满文字的文本文件。
  • 按字母顺序排列。

标签: java search binary


【解决方案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++
}

while 中的 lowIndex++ 不是必需的,因为它更新了 lowIndex,而与 BS 算法根据与 midIndex 值的比较更新索引无关。

【讨论】:

  • 在while条件中使用&lt;=如果搜索词不在数组中会导致死循环。
  • 谢谢,成功了!您能否简单解释一下为什么/如何?
  • @JimGarrison 更新了无限循环条件的返回
  • 这段代码既丑又丑。二进制搜索不需要这样的东西。来吧,算法在Wikipedia page 上以可以很容易地用Java 表达的形式简单地给出。
  • @Jim Garrison 这些是我的任务要求,我很欣赏 nullpointer 的建议,即使它们“笨拙且丑陋”。
猜你喜欢
  • 2011-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-07
  • 2020-06-19
相关资源
最近更新 更多