欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java源码分析(1):二分查找 + 循环递归实现

程序员文章站 2022-07-10 20:57:11
源代码 "源码地址" 思考 为啥是mid + 1 ,mid 1就一个下标感觉没差啊。 回答:调试之后再回想,发现没有什么差别,最终收拢到 low == high 的时候都能算出来,不会错过。 自己手打的代码 ......

源代码

源码地址

    public static int binarySearch(int[] a, int key) {
        return binarySearch0(a, 0, a.length, key);
    }

    public static int binarySearch(int[] a, int fromIndex, int toIndex,
                                   int key) {
        rangeCheck(a.length, fromIndex, toIndex);
        return binarySearch0(a, fromIndex, toIndex, key);
    }


    // Like public version, but without range checks.
    private static int binarySearch0(int[] a, int fromIndex, int toIndex,
                                     int key) {
        int low = fromIndex;
        int high = toIndex - 1;

        while (low <= high) {
            int mid = (low + high) >>> 1;
            int midVal = a[mid];

            if (midVal < key)
                low = mid + 1;
            else if (midVal > key)
                high = mid - 1;
            else
                return mid; // key found
        }
        return -(low + 1);  // key not found.
    }

思考

为啥是mid + 1 ,mid - 1就一个下标感觉没差啊。

回答:调试之后再回想,发现没有什么差别,最终收拢到 low == high 的时候都能算出来,不会错过。

自己手打的代码

public class Source1_BinarySearch {
    public static int binarySearch(int[] a, int fromIndex, int toIndex, int key) {

        int low = fromIndex;
        int high = toIndex - 1;
        while (low <= high) {
            int mid = (low + high) >> 1;
            int midValue = a[mid];
            // 小于 lo 指向中间,大于hi指向中间,等于直接返回
            if (midValue < key)
                low = mid + 1;
            else if (midValue > key)
                high = mid - 1;
            else
                return mid;
        }
        return -1;
    }

    public static int binarySearch_Recursive(int[] a, int fromIndex, int toIndex, int key) {
        int low = fromIndex;
        int high = toIndex - 1;
        int result = -1;
        if (low <= high) {
            int mid = (low + high) >>> 1;
            int midValue = a[mid];
            if(midValue < key)
                result = binarySearch_Recursive(a,mid +1,high + 1,key);
            else if  (midValue > key)
                result = binarySearch_Recursive(a,low,mid + 1 -1,key);
            else
                return mid;
        }
        return result;
    }

    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int index = binarySearch_Recursive(a, 0, a.length, 11);
        System.out.println(index);
    }
}