调用二进制搜索方法的正确方法是什么

时间:2012-05-27 17:08:28

标签: java search recursion binary

假设我有一个10个整数的数组,我正在使用二进制搜索来查找数字,让我们以数字为例

1 2 3 4 5 6 7 8 9 10

我正在使用这种方法

static void binarySearch(int n, int[] a, int low, int high)
    {
        int mid = (high + low) / 2;
        if(low > high)
            System.out.println(n+" was not found after "+counter+" comparisons");
        else if(a[mid] == n)
        {
            counter++;
            System.out.println(n+" was found at position "+mid+" after "+counter+" comparisons");
        }            
        else if(a[mid] < n)
        {
            counter++;
            binarySearch(n, a, mid+1, high);
        }            
        else
        {
            counter++;
            binarySearch(n, a, low, mid-1);
        }            
    }

调用方法binarySearch(5,a,0,a.lenght)的正确方法是什么 要么 binarySearch(5,a,0,a.lenght-1)

我知道他们都会找到这个号码,但他们会在不同的索引中找到它;从而进行更多的比较

3 个答案:

答案 0 :(得分:2)

正确的方法是避免使用这种方法,并使用标准Arrays.binarySearch()方法,该方法具有记录的巨大优势,以及返回结果的另一个巨大优势,而不是在System.out上打印它(这使它无用)。

答案 1 :(得分:1)

我们应该做一些测试吗?

首先,让我们搜索数组中的每个数字。我们得到:

binarySearch(i, array, 0, array.length);

1 was found at position 0 after 3 comparisons
2 was found at position 1 after 4 comparisons
3 was found at position 2 after 2 comparisons
4 was found at position 3 after 3 comparisons
5 was found at position 4 after 4 comparisons
6 was found at position 5 after 1 comparisons
7 was found at position 6 after 3 comparisons
8 was found at position 7 after 4 comparisons
9 was found at position 8 after 2 comparisons
10 was found at position 9 after 3 comparisons
Average: 2.9 comparisons

binarySearch(i, array, 0, array.length - 1);

1 was found at position 0 after 3 comparisons
2 was found at position 1 after 2 comparisons
3 was found at position 2 after 3 comparisons
4 was found at position 3 after 4 comparisons
5 was found at position 4 after 1 comparisons
6 was found at position 5 after 3 comparisons
7 was found at position 6 after 4 comparisons
8 was found at position 7 after 2 comparisons
9 was found at position 8 after 3 comparisons
10 was found at position 9 after 4 comparisons
Average: 2.9 comparisons

如您所见,差异确实会出现,但平均值保持不变。 现在让我们测试更大的数字:

100000 items
binarySearch(i, array, 0, array.length);
Average: 15.68946 comparisons
binarySearch(i, array, 0, array.length - 1);
Average: 15.68946 comparisons

200000 items
binarySearch(i, array, 0, array.length);
Average: 16.689375 comparisons
binarySearch(i, array, 0, array.length - 1);
Average: 16.689375 comparisons

500000 items
binarySearch(i, array, 0, array.length);
Average: 17.951464 comparisons
binarySearch(i, array, 0, array.length - 1);
Average: 17.951464 comparisons

因此,平均而言,它不会走向任何一种方式。为了惯例,我建议使用独有的上限版本:binarySearch(i, array, 0, array.length);

答案 2 :(得分:0)

可以提出这样的问题:正确的包容性 [低,高] 还是正确的 [低,高] ?这种独特的形式具有由Dijkstra“创立”的悠久计算机科学传统。在我看来,它也更优雅(a.length而不是a.length-1)。

但是在你的函数中它是[低,高],a.length-1,因为你看到低&gt;高(不低> =高)和(低,中1)(不是(低,中))。