在使用Arrays.binarySearch()的时候要注意先对数组进行排序。
Arrays.binarySearch()方法介绍:
Searches the specified array of ints for the specified value using the binary search algorithm. The array must be sorted (as by the sort(int[]) method) prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found.
int as[] = {32,4,5,4,36,54,4,543,1};
Arrays.sort(as);
for (int i:as) {
System.out.println(i);
}
int index = Arrays.binarySearch(as,4);//二分法查找
System.out.println("index" + index);
输出结果:
1
4
4
4
5
32
36
54
543
index1