繁体   English   中英

二元搜索的比较次数

[英]Number of Comparisons Made by a Binary Search

是否可以计算递归二进制搜索的比较次数? 如果是这样,怎么办?

这是我指的搜索:

//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

在方法之外声明您的count变量。 然后,在每次调用该方法时加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

如果希望呼叫者能够访问该计数,最可能的方法是将累加器传递到二进制搜索中。 在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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM