我想知道为什么当我提供一个不在我的数组中的字母时,这个方法给了我一个ArrayIndexOutOfBounds
异常。如果键不是字母,那么返回值似乎没有问题。
public class BinarySearch2 {
public static void main(String[] args) {
String[] array = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
String key = "K";
String found = binarySearch(array, key);
System.out.println(found);
}
public static String binarySearch(String[] array, String key) {
int low = 0;
int high = array.length;
int mid = (low + high)/2;
//int i = 0;
while (low <= high) {
//System.out.print(i + " ");
if (array[mid].compareTo(key) < 0) {
System.out.println(array[mid].compareTo(key));
low = mid + 1;
mid = (low + high)/2;
}
else if (array[mid].compareTo(key) > 0) {
high = mid - 1;
mid = (low + high)/2;
}
else
return array[mid];
//i++;
}
return "-1";
}
}
答案 0 :(得分:2)
在binarySearch
方法中,您已将high
初始化为: -
int low = 0;
int high = array.length;
int mid = (low + high)/2;
高实际应该是: -
int high = array.length - 1;