1. 程式人生 > >基礎演算法 - 二分查詢

基礎演算法 - 二分查詢


public class Main {

    private static int binary_search(int[] x, int key) {
        int l = 0, r = x.length - 1;
        while (l <= r) {
            int m = (l + r) >>> 1;
            if (x[m] == key) {
                return m;
            } else if (x[m] < key) {
                ++ l;
            } else {
                -- r;
            }
        }
        return -1;
    }

    private static int lower_bound(int[] x, int key) {
        int first = 0;
        int len = x.length;
        while (len > 0) {
            int half = len >>> 1;
            int m = first + half;
            if (x[m] < key) {
                // 右半區
                first = m + 1;
                len -= half + 1;
            } else {
                // 左半區
                len = half;
            }
        }
        return first;
    }

    private static int upper_bound(int[] x, int key) {
        int first = 0;
        int len = x.length;
        while (len > 0) {
            int half = len >>> 1;
            int m = first + half;
            if (x[m] <= key) {
                // 右半區
                first = m + 1;
                len -= half + 1;
            } else {
                // 左半區
                len = half;
            }
        }
        return first;
    }

    public static void main(String[] args) {
    }
}