【发布时间】:2012-06-02 07:07:30
【问题描述】:
假设我有一个由 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)
我知道他们都会找到这个数字,但他们会在不同的索引处找到它;从而进行更多比较
【问题讨论】:
-
你都试过了吗?尝试添加一些调试打印,以便您了解发生了什么。
标签: java search recursion binary