美文网首页
二分查找

二分查找

作者: 猴子扔飞镖 | 来源:发表于2018-12-18 12:52 被阅读0次

    long[] a = {1, 2, 3, 4, 7, 3, 5, 10, 23, 89, 44};
    int i = binarySearch(a, 4);
    System.out.println(i);

    public static int binarySearch(long[] a, long key) {

        int low = 0;
        int high = a.length - 1;
    
        while (low <= high) {
            int mid = (low + high) >>> 1;
            long midVal = a[mid];
    
            if (midVal < key) {
                low = mid + 1;
            } else if (midVal > key) {
                high = mid - 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

    相关文章

      网友评论

          本文标题:二分查找

          本文链接:https://www.haomeiwen.com/subject/tgnkkqtx.html