【发布时间】:2021-10-16 07:57:20
【问题描述】:
我在我的程序中实现了这个二分搜索算法,它实现了 Comparator 接口。本质上,我想让这个方法递归,但我一直没有这样做。我想知道这样做是否合适。
public static <Key> int firstIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
if (a == null || key == null || comparator == null) {
throw new NullPointerException("Arguments cannot be null.");
}
int low = 0,
high = a.length - 1;
if (comparator.compare(a[0], key) == 0) {
return 0; // Non-recursive base case.
}
while (low <= high) {
int mid = low + (high - low) / 2;
// For key, we are searching for the first occurrence.
// Comparator: compare the key is being sorted with.
if (comparator.compare(key, a[mid]) < 0) high = mid - 1;
else if (comparator.compare(key, a[mid]) > 0) low = mid + 1;
else if (comparator.compare(a[mid - 1], a[mid]) == 0) high = mid - 1;
else return mid;
}
return -1; // Index of the first occurrence of an element matching key in a[].
}
【问题讨论】:
-
1) 你试过什么? 2)它可能是合适的,但如果迭代方式有效,那你为什么要这样做?
-
代码工作得非常好,但我想我开始倾向于让我的大部分方法递归。感谢您将问题更改为更合适的内容,也感谢您回复。
-
这很好,但你到底有哪些尝试“失败”了?你得到什么错误?您对流程有哪些具体问题?
-
注意 - 递归解决方案更有可能出现堆栈溢出错误。如果有一个简单的迭代解决方案更可取。
标签: java arrays binary-search