Java 10无法通过二进制搜索找到正确的值

时间:2018-07-16 13:55:12

标签: java binary-search

public class BinarySearch {
    private static int search(int key, int[] a) {
        int lo = 0;
        int hi = a.length - 1;
        while (lo <= hi) {
            int mid = (lo + hi) >>> 1;
            int midVal = a[mid];
            if (key < midVal) {
                hi = mid - 1;
            } else if (key > midVal) {
                lo = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] list = {
                100, 500, 300,
                400, 200, 600,
                900, 800, 700
        };
        int key = 500;
        int result = search(key, list);
        System.out.println(result);
    }
}

key = 100 or 200可以输出0或4时,但是当我让key等于或大于500时,程序总是输出-1。

Java版本:10.0.1

0 个答案:

没有答案