我试图在给定元素的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