【问题标题】:Finding number of comparisons查找比较次数
【发布时间】:2020-10-22 13:52:48
【问题描述】:

我正在尝试跟踪此二进制搜索代码中的键比较次数。对于2^16 的数组大小,比较结果应该在 17 左右。你能解释一下为什么我会变成 33 岁吗?

public class AdvancedBinarySearch {

    int count = 0;

    // Returns location of key, or -1 if not found 
    int AdvancedBinarySearch(int arr[], int l, int r, int x) {
        int m;

        while (r - l > 1) {
            count++;
            m = l + (r - l) / 2;
            if (arr[m] <= x) {
                l = m;
                count++;
            } else {
                r = m;
                count++;
            }
        }

        if (arr[l] == x) {
            count++;
            return l;
        }

        if (arr[r] == x) {
            count++;
            return r;

        } else {
            count++;
            return -1;

        }
    }

    public void setCount(int i) {
        this.count = i;
    }
}

【问题讨论】:

  • 您能否提供一个示例程序来运行它并重现该数字?
  • 您在while 循环中的比较之前之后 都碰到了count。因此,您的结果大约是您预期的两倍也就不足为奇了。

标签: java binary-search bug-tracking


【解决方案1】:

您的代码计算了两次if (arr[m] &lt;= x) 比较。如果您从l = m 下方以及r = m 下方移除count++,则不会再发生这种情况。

我在此更改之前和之后对此进行了测试,并在从 0 到 65535 的整数数组中搜索了 189。该数组的大小为 2^16,在更改之前,计算了 33 次比较,更改之后,计算了 17 次比较,因此我认为此更改符合您的要求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    相关资源
    最近更新 更多