【问题标题】:Recursive binary search returning a stackoverflow error when word doesn't exist当单词不存在时,递归二进制搜索返回 stackoverflow 错误
【发布时间】:2021-06-14 17:21:48
【问题描述】:

我写了一个递归二进制搜索方法,如果字典中存在这个词,它就可以工作,但是,当我输入一个不存在的词时,比如“rwetjia”,我得到一个stackoverflow错误

    public boolean wordCheck(String target, int start, int end) {
    target.toLowerCase();
    if (end >= 1) {
        int middle = start + (end - start) / 2;
        int targetside = target.compareTo(words.get(middle));// Finds which side the word is on
        if (targetside == 0) {
            return true;
        } // Word is at the middle (the word exists and has been found)
        else if (targetside > 0) {
            return wordCheck(target, middle + 1, end);
        } // If target word is on the right side of the array, "cuts" the other half off
        else {
            return wordCheck(target, start, middle - 1);
        }
    } // If target word is on the left side of the array, "cuts" the other half off
        return false; // Word is not in the dictionary
}

【问题讨论】:

  • 当你进入调用这个的循环时,你认为会发生什么? return wordCheck(target, middle + 1, end);你会陷入无限循环
  • 什么是end?最后一个元素的索引,还是最后一个元素的索引加一?换句话说,要在完整列表中搜索,您会调用wordCheck(target, 0, words.size()) 还是wordCheck(target, 0, words.size()-1)

标签: java binary-search


【解决方案1】:

问题在于您的结束条件,即“end >= 1”。 例如,假设您输入的单词比列表中的任何单词都小。在我的示例中,现在我在某个地方,start = 3 和 end = 10。这为您提供了以下迭代:

Iteration. Start - End - Middle
1. 3 - 10 - 6.5
2. 6 - 10 - 8
3. 9 - 10 - 9.5
4. 10 - 10 - 10
5. 11 - 10 - 10.5

你要做的是检查我猜是否“开始

【讨论】:

    【解决方案2】:

    试试:

    if (end >= start) {
    

    而不是

    if (end >= 1) {
    

    更新:

    我假设end 是要考虑的最后一个元素的索引(请参阅我上面的评论);否则,测试将是:

    if (end > start) {
    

    你需要更换:

            return wordCheck(target, start, middle - 1);
    

    与:

            return wordCheck(target, start, middle);
    

    【讨论】:

    • 是的,索引是要考虑的最后一个元素
    • 另外,是的,您的解决方案有效,谢谢!我相当确定我有 end >= start 在某个时间点,但最终以 end >= 1 结束。
    猜你喜欢
    • 2013-12-24
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 2021-03-31
    • 2020-01-15
    相关资源
    最近更新 更多