Arrays.binarySearch是系统库提供的二分查找api。
先看看源代码中的注释
/**
* Searches the specified array of ints for the specified value using the
* binary search algorithm. The array must be sorted (as
* by the {@link #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.
**/
这说明:该api只能用于有序递增数组(所以一般配合Arrays.sort使用),且数组中若有重复值,无法保证获得哪个值
重载“狂魔”
首先提及一下,该api提供了多个重载方法。支持八大基本类型除了boolean外(毕竟boolean数组也跟查找没多大关系),还支持Object类型和泛型,可以说是应有尽有。
此处以int类型为例说明,其它实现也大同小异
public static int binarySearch(int[] a, int key) {
return binarySearch0(a, 0, a.length, key);
}
public static int binarySearch(int[] a, int fromIndex, int toIndex,int key) {
rangeCheck(a.length, fromIndex, toIndex);
return binarySearch0