码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-05-17 17:22:58      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:实现   调试   key   idv   min   rgs   res   ike   git   

源代码

源码地址

    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源码分析(1):二分查找 + 循环递归实现

标签:实现   调试   key   idv   min   rgs   res   ike   git   

原文地址:https://www.cnblogs.com/kumaxiong/p/9052069.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!