我試圖在給定元素的java數組中實現三元搜索。此時,我在數組的下三分之一處得到一個StackOverflowError,而在中間的三分之一處得到不正確的結果。非常感謝。Java中的遞歸三元搜索:將數組分爲三部分,並遞歸搜索給定元素
public class TernarySearch {
static int[] ints = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
public static int search(int[] a, int x, int low, int high) {
// int mid = (high + low)/2;
int thirdile = a.length/3;
// System.out.println(a.length/3);
// System.out.println(thirdile);
if (low > high) {
System.out.println("low is greater than high. Item not found.");
return 0;
} else if (x > a[(high-(thirdile - 1))]) { // upper third
System.out.println("X is greater than mid. higher third.");
return search(a, x, (high - thirdile), high);
} else if (x > a[thirdile - 1] && x < (high -thirdile)) { // middle third
System.out.println("X is in the middle third.");
return search(a, x, thirdile + 1, (high - thirdile) - 1);
} else if (x < a[thirdile -1 ]) { // lower third
System.out.println("X is less than thirdile. lower third.");
return search(a, x, low, thirdile);
}
else {
System.out.println("Found it at first thirdile");
return thirdile;
}
}
public static void main(String[] args) {
System.out.println(search(ints, 2, 0, ints.length - 1));
}
}
這個'&& X <(高-thirdile)'似乎沒有必要 – MeBigFatGuy
我要段搜索到三三(你會與兩半),所以它的意思劃分中間陣列的第三部分。沒有它,搜索會跨越陣列的三分之二。 – user1070619