【问题标题】:Number of Comparisons Made by a Binary Search二分搜索进行的比较次数
【发布时间】:2014-06-21 05:48:26
【问题描述】:

是否可以计算递归二分查找的比较次数?如果有,怎么做?

这是我指的搜索:

//binary search
public static int binarySearch(int[] items, int start, int end, int goal)
{
    if (start > end)
        return (-1);
    else
    {
        int mid = (start + end)/2;
        if (goal == items[mid])
            return (mid);
        else
        if (goal < items[mid])
            return (binarySearch(items, start, mid - 1, goal));
        else
            return (binarySearch(items, mid + 1, end, goal));
    }
}//end binarySearch

【问题讨论】:

    标签: java search count binary


    【解决方案1】:

    在方法之外声明您的计数变量。然后每次调用该方法时加 1。

    long count = 0;
    //binary search
    public static int binarySearch(int[] items, int start, int end, int goal)
    {
        count += 1
        if (start > end)
            return (-1);
        else
        {
            int mid = (start + end)/2;
            if (goal == items[mid])
                return (mid);
            else
            if (goal < items[mid])
                return (binarySearch(items, start, mid - 1, goal));
            else
                return (binarySearch(items, mid + 1, end, goal));
         }
    }//end binarySearch
    

    【讨论】:

    • 使用long的任何具体原因?
    • @MattiVirkkunen 我更喜欢持久的代码,但正如您似乎表明的那样,是的,除非您的搜索空间的大小远远超过 10^50 或同样大的数字,否则二进制搜索不太可能需要很长时间.鉴于count 仅初始化一次,它不会产生显着的性能开销。
    • 这不仅不太可能而且不可能,因为定义范围的参数是ints,更不用说二进制搜索在日志时间或更长时间内运行的事实。即使使用long 范围,您也只需要byte count。但我认为int 仅对于您的平均整数值最具可读性。
    • @MattiVirkkunen 是的,这是习惯的力量。我已经编写了足够多的计时器和搜索代码,以至于我本能地声明了 count 变量。感谢您的提示,我会尽我所能保持我的直觉。似乎依靠直觉有点赌博;它需要认真的经验才能可靠。
    【解决方案2】:

    如果您希望调用者能够访问计数,您最可能的方法是将累加器传递到您的二进制搜索中。在 java 7 或更低版本中,AtomicLong 可能是一个不错的选择(尽管它确实有一些开销)。在 java 8 中,LongAdder 也不错:

    public static int binarySearch(int[] items, int start, int end, int goal, AtomicLong counter) {
    
    }
    

    每次进行比较时,您只需增加计数:

    counter.incrementAndGet()
    

    当您退出搜索时,计数器将包含比较次数:

    long count = counter.get()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-10
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      • 2022-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多