二分查找

 public static void main(String[] args) {
        int[] array = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38};
        int k = binarySerach(array, 2);
        System.out.println(" **** " + k);
    }
 /**
     * 二分查找,找到该值在数组中的下标,否则为-1
     */
    static int binarySerach(int[] array, int key) {
        int left = 0;
        int right = array.length - 1;

        // 这里必须是 <=
        while (left <= right) {
            int mid = (left + right) / 2;
            System.out.println("left=" + left + "   right=" + right + "  长度=" + (left + right));
            System.out.println("分割值 " + mid);
            if (array[mid] == key) {
                return mid;
            } else if (array[mid] < key) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return -1;
    }

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