二分查找 Arrays.binarySearch(a, key)的源码

1.查看Arrays.binarySearch(a, key)的源码,可以发现它的实现为:

public static int binarySearch(int[] a, int key) {
        return binarySearch0(a, 0, a.length, key);
    }
2.查看binarySearch0(a, 0, a.length, key)的源码为:
 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.
    }

你可能感兴趣的:(个人笔记)