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

Posted 豆腐抹上墙

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java源码分析:二分查找 + 循环递归实现相关的知识,希望对你有一定的参考价值。

源代码

源码地址

    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);
    }
}

以上是关于Java源码分析:二分查找 + 循环递归实现的主要内容,如果未能解决你的问题,请参考以下文章

二分查找算法的递归循环实现及其缺陷

python递归函数及二分法查找

7JS实现二分查找

找数字(递归,二分查找)

Day589.二分查找(非递归) -数据结构和算法Java

java 二分查找法