binary search(java)

public static int binarySearch(final long key, final long arr[]) {

    int lowerBound = 0;
    int upperBound = arr.length - 1;

    int curIn;

    while (true) {
        curIn = (lowerBound + upperBound) / 2;
        if (arr[curIn] == key) {
            return curIn;
        } else if (lowerBound > upperBound) {
            return arr.length;
        } else {
            if (arr[curIn] < key) {
                lowerBound = curIn + 1;
            } else {
                upperBound = curIn - 1;
            }
        }
    }
}

你可能感兴趣的:(二分查找)