假设我有一个 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)的正确方法是什么 或者 二进制搜索(5, a, 0, a.lenght-1)
我知道他们都会找到该号码,但他们会在不同的索引处找到它;从而进行更多比较
最佳答案
正确的方法是避免这种方法,而使用标准的Arrays.binarySearch()方法,它的巨大优势是被记录下来,另一个巨大的优势是返回结果,而不是将其打印在 System.out 上(这使得它变得毫无用处)。
关于java - 调用二分查找方法的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10775773/