查找-二分查找

参考:https://www.cnblogs.com/lsqin/p/9342929.html

源码:https://github.com/sunrui849/selectAlgorithm

目录:顺序查找

二分查找

插值查找

斐波那契查找

分块查找

哈希查找

二叉树查找

红黑树查找

二分查找

算法简介

    二分查找(Binary Search),是一种在有序数组中查找某一特定元素的查找算法。查找过程从数组的中间元素开始,如果中间元素正好是要查找的元素,则查找过程结束;如果某一特定元素大于或者小于中间元素,则在数组大于或小于中间元素的那一半中查找,而且跟开始一样从中间元素开始比较。如果在某一步骤数组为空,则代表找不到。
    这种查找算法每一次比较都使查找范围缩小一半。

算法描述 

    给予一个包含 n个带值元素的数组A 

        1、 令 L为0 , R为 n-1 ;
        2、 如果L>R,则搜索以失败告终 ;
        3、 令 m (中间值元素)为  ⌊(L+R)/2⌋;
        4、 如果 Am<T,令 L为 m + 1 并回到步骤二 ;
        5、 如果 Am>T,令 R为 m - 1 并回到步骤二;

复杂度分析 

    时间复杂度:折半搜索每次把搜索区域减少一半,时间复杂度为 O(logn) 
    空间复杂度:O(1)

算法实现

/**
     * 非递归写法
     * @param list
     * @param selectValue
     * @return
     */
    private static int select2(List<Integer> list, int selectValue) {
        if (list == null || list.isEmpty()){
            return -1;
        }
        int start = 0;
        int end = list.size() - 1;
        while (end > start) {
            int middleIndex = (end + start)/2;
            if (list.get(middleIndex) > selectValue) {
                end = middleIndex;
            } else if (list.get(middleIndex) < selectValue) {
                start = middleIndex + 1;
            } else {
                return middleIndex;
            }
        }

        return -1;
    }



    /**
     * 递归写法
     * @param list
     * @param selectValue
     * @return
     */
    private static int select(List<Integer> list, int selectValue) {
        if (list == null || list.isEmpty()){
            return -1;
        }
        return loopSelect(list, 0, list.size() - 1 , selectValue);
    }

    private static int loopSelect(List<Integer> list, int startIndex, int endIndex, int selectValue){
        if (startIndex == endIndex) {
            return list.get(startIndex) == selectValue ? startIndex : -1;
        }

        int middleIndex = (endIndex + startIndex)/2;

        if (list.get(middleIndex) > selectValue){
            return loopSelect(list, startIndex, middleIndex, selectValue);
        }else if (list.get(middleIndex) < selectValue) {
            return loopSelect(list, middleIndex + 1, endIndex, selectValue);
        }

        return middleIndex;
    }

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值