【问题标题】:Binary Search compareTo String objects二进制搜索 compareTo 字符串对象
【发布时间】:2016-10-14 11:07:05
【问题描述】:
class ObjectBinarySearcher{

    public static int search(String[] array, String value){

        int first = 0, last = array.length-1, position = -1;
        boolean found = false;

        while(!found && first < last){
            int mid = (first+last)/2;
            int midValue = array[mid].compareTo(value);

            if(midValue==0){
                position = mid;
                found = true;
            }
            else if(midValue<0)
                last = mid-1;
            else
                first = mid+1;
        }

        return position;
    }
}

我正在发送一个包含{“love”、“hate”、“happy”、“sad”、“neutral”}的数组,每次我尝试使用我的二进制搜索方法搜索“neutral”时,它告诉我它没有找到。是什么导致这种情况发生?

【问题讨论】:

  • 您的输入数组是否已排序?你在发送["happy", "hate", "love", "neutral", "sad"] 吗?
  • 是的,排序在我的主要方法中。

标签: java arrays sorting binary-search compareto


【解决方案1】:
  1. 您的输入数组必须经过排序才能使用二分搜索。

  2. 正如@Libby 指出的那样,您的 while 循环需要更改以允许 first 小于或等于 last。

  3. 如果first == last时没有找到匹配,则需要能够退出循环。

  4. 如果 midValue

新代码

while (!found && first <= last) { // allow first to be lower or equal to last
    int mid = (first + last) / 2;
    int midValue = array[mid].compareTo(value);

    if (midValue == 0) { // matched!

        position = mid;
        found = true;

    } else if (first == last) { // didn't match and there was only one left to check

        break; // so break out of the loop

    } else if (midValue < 0) { // current pos is too low

        first = mid + 1; // so adjust the lower bound

    } else { // current pos is too high

        last = mid - 1; // so adjust the upper bound

    }
}

【讨论】:

  • 我添加了另一个终止案例,但它仍然告诉我没有找到中性。另外,正如我提到的@Jason,它在我的主要方法中排序。
  • 已编辑以解决您的问题 - 当数组项太低时您正在移动上限(反之亦然),这与您需要做的相反。
  • 这样它确实在元素 4 处找到“中性”,但现在在重新运行搜索后(使用 do-while 循环),它现在表明在元素 4 处找到了“sad”。
【解决方案2】:

while loop 更改为while(!found &amp;&amp; first &lt;= last)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多