拙劣算法:手写二分法

关键点:1.二分法退出条件start=end
2.选择中间数(start + end) / 2
3.命中就return

    static int dichotomy(int[] input,int target) {
        if (input == null) {
            return -1;
        }
        int start = 0;
        int end = input.length -1;
        while (start != end) {
            int middle = (start + end) / 2;
            System.out.println("start = " + start + ",end = " + end + ",middle = " + middle);
            if (input[middle] == target) {
               return middle;
            }
            System.out.println("middle is " + middle);
            if (input[middle] > target) {
                end = middle - 1;
            } else if (input[middle] < target) {
                start = middle + 1;
            }

        }
        return -1;
    }

妈呀,居然完全正确!!

你可能感兴趣的:(拙劣算法:手写二分法)