хорошо, так что я знаю, что эта проблема старая. Но я хотел бы опубликовать ответ для будущих людей, которые ищут это. Ваш код делает странные вещи с третьим.
также в ваших заявлениях if не все включено. Вы пропускаете разные -1 или имеете -1, когда не должны. Также в ваших рекурсивных вызовах вы не всегда меняете низкий или высокий уровень на тот, который должен быть. Надеюсь, этот код поможет людям
public class TernarySearch {
static int[] ints = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
public static int search(int[] a, int key, int low, int high) {
// int mid = (high + low) / 2;
//int thirdile = (high + low)/3
int firstThird = ((high+1)-low)/3;
int secondThird = ((2*((high+1)-1))/3);
// System.out.println(a.length/3);
// System.out.println(thirdile);
if (low > high) {
System.out.println("low is greater than high."+ key +" not found.");
return -1;
} else if (key > a[secondThird]) { // upper third
System.out.println("key is greater than secondThird. its in higher third.");
return search(a, key, secondThird+1, high);
} else if (key > a[firstThird]) { // middle third
System.out.println("key is in the middle third.");
return search(a, key, firstThird+1, secondThird);
// high is secondThird, because it could be equal to the secondThird still
// all we know is that it wasn't higher than a[secondThird], but was higher
//than a[firstThird]
} else if (key < a[firstThird]) { // lower third
System.out.println("key is less than thirdile. lower third.");
return search(a, key, low, firstThird-1);
}
else {
System.out.println("Found it at first third at index: "+firstThird);
return firstThird;
}
}
public static void main(String[] args) {
System.out.println(search(ints, 2, 0, ints.length - 1));//print out the index number that is returned
//if it is -1 that is printed out, 2 wasn't found, else it was found
int myKeyIndex = search(ints, 2, 0, ints.length-1);
if(myKeyIndex != -1)
System.out.println(ints[myKeyIndex]+ "was found in the array!!");
else
System.out.println("Didn't find the key!!");
}
}