对于这个问题咋们看下它的内置源码就知道了:
public static int binarySearch(int[] a, int key) {
return binarySearch0(a, 0, a.length, key);
}
binarySearch0方法的源码:
private static int binarySearch0(int[] a, int fromIndex, int toIndex,int key) {
int low = fromIndex;
int high = toIndex - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = a[mid];
if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
代码System.out.println(Arrays.binarySearch(a,9))的输出结果也就是binarySearch0的返回结果
这个数组是无序的,输出的结果是不确定的。调用之前必须对数组进行排序。