我不知道为什么这个方法会抛出 ArrayIndexOutOfBounds 异常。
When I change the initial "high"
值,我搜索"int high = array.length - 1;"
的程序将。return any integer value
我究竟做错了什么?
提前致谢!
public class BinarySearch {
public static void main(String[] args) {
int searchValue = 12;
int[] givenNums = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
binarySearch(givenNums, searchValue);
System.out.println("\nResult: " + searchValue);
}
public static int binarySearch(int[] array, int key) {
int low = 0;
int high = array.length;
int mid = (low + high) / 2;
int i = 0;
System.out.println();
while (low <= high) {
System.out.print(i + " ");
if (array[mid] < key) {
low = mid + 1;
mid = (low + high) / 2;
} else if (array[mid] > key) {
high = mid - 1;
mid = (low + high) / 2;
}
else
return mid;
i++;
}
return -1;
}
}