二分查找

public class Test2 {

    public static void main(String[] args) {
        int[] array = new int[]{2, 4, 7, 9, 10, 55, 67};
        System.out.println(binarySearch(array, 1));
    }

    public static int binarySearch(int[] array, int x) {
        if (null == array) {
            return -1;
        }

        int begin = 0;
        int end = array.length - 1;

        while (begin <= end) {
            int middle = (begin + end) / 2;
            if (array[middle] == x) {
                return middle;
            } else if (array[middle] > x) {
                end = middle - 1;
            } else {
                begin = middle + 1;
            }
        }
        return -1;
    }
}

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