Arrays.binarySearch()

public int binarySearch(int[] a, int fromIndex, int toIndex, int x) {
        int lo = fromIndex, hi = toIndex-1;

        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if      (x > a[mid]) lo = mid + 1;
            else if (x < a[mid]) hi = mid - 1;
            else                      return mid;
        }

        return -(lo+1);
    }
int index = binarySearch(a, i, j, x);
if (index < 0)-(index + 1)  就是x该插入的位置

你可能感兴趣的:(基础算法)