我在我的程式中實作了這個二分搜索演算法,它實作了 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[].
}
uj5u.com熱心網友回復:
你通過high和low方法。創建采用這些附加引數的方法的另一個版本,創建它private并使用0和a.length - 1為新引數呼叫它。喜歡,
public static <Key> int firstIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
return firstIndexOf(a, key, comparator, 0, a.length - 1);
}
然后簡單地用遞回呼叫替換回圈。喜歡,
private static <Key> int firstIndexOf(Key[] a, Key key, Comparator<Key> comparator, int low, int high) {
if (a == null || key == null || comparator == null) {
throw new NullPointerException("Arguments cannot be null.");
}
if (comparator.compare(a[0], key) == 0) {
return 0; // Non-recursive base case.
}
if (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)
return firstIndexOf(a, key, comparator, low, mid - 1);
else if (comparator.compare(key, a[mid]) > 0)
return firstIndexOf(a, key, comparator, mid 1, high);
else if (comparator.compare(a[mid - 1], a[mid]) == 0)
return firstIndexOf(a, key, comparator, low, mid - 1);
else
return mid;
}
return -1; // Index of the first occurrence of an element matching key in a[].
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/318327.html
