int arr[]=new int[]{4,25,10};
Array.sort(arr);
int index=Arrays.binarySearch(arr,0,1,8);上面代码index为何等于-2?8不是应该在10的前面吗?10的索引值不是1吗?我觉得index的值应该是-1
Array.sort(arr);
int index=Arrays.binarySearch(arr,0,1,8);上面代码index为何等于-2?8不是应该在10的前面吗?10的索引值不是1吗?我觉得index的值应该是-1
这个方法只适合在有序数组中操作。
Searches the specified array of bytes for the specified value using the binary search algorithm.
static int binarySearch(char[] a, char key)
Searches the specified array of chars for the specified value using the binary search algorithm.
static int binarySearch(double[] a, double key)
Searches the specified array of doubles for the specified value using the binary search algorithm.
static int binarySearch(float[] a, float key)
Searches the specified array of floats for the specified value using the binary search algorithm.
static int binarySearch(int[] a, int key)
Searches the specified array of ints for the specified value using the binary search algorithm.
static int binarySearch(long[] a, long key)
Searches the specified array of longs for the specified value using the binary search algorithm.
static int binarySearch(Object[] a, Object key)
Searches the specified array for the specified object using the binary search algorithm.
static int binarySearch(short[] a, short key)
Searches the specified array of shorts for the specified value using the binary search algorithm.
static
<T> int
binarySearch(T[] a, T key, Comparator<? super T> c)
Searches the specified array for the specified object using the binary search algorithm.Sun公司的API里没有重载你这个方法啊你是不是自己重写了啊如果重写了,把Arrays的代码贴出来吧。
代码中有“Array.sort(arr);
”
排序了啊!
private static int binarySearch0(int[] a, int fromIndex, int toIndex,
int key) {
int low = fromIndex; //0
int high = toIndex - 1; 0 while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = a[mid]; if (midVal < key)
low = mid + 1; //1
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found. // - 2
}
结果是-2 你可以对着源码看看。