利用二分查找法查找数组中的连续的一段数据(前提数组有序)

##利用二分查找法查找数组中的连续的一段数据(前提数组有序)
最近在做一个项目,向ElasticSearch(简称ES)发送http请求,然后ES返回数据,由于ES返回的数据量非常大,又需要从其中查询业务数据,因此想起了二分查找法查询数据。
算法需求:任意给两个数据A,B(A<=B),在数组arry[]中,找到集合(a,b)<=(A,B),返回子集合(a,b)。
代码如下:
二分查找算法:

    public Pair<Integer, Integer> Binary_search(List<Integer> srcList, int begin, int end) {
        int beginLeft = 0;
        int beginRight = srcList.size() - 1;
        int endLeft = 0;
        int endRight = srcList.size() - 1;
        if (begin <= srcList.get(beginLeft) && end >= srcList.get(endRight)) {
            return new Pair<>(beginLeft, endRight);
        }
        while ((beginRight - beginLeft > 1) || (endRight - endLeft > 1)) {
            int beginMid = (beginLeft + beginRight) / 2;
            int endMid = (endLeft + endRight) / 2;
            if (begin >= srcList.get(beginMid)) {
                beginLeft = beginMid;
            } else {
                beginRight = beginMid;
            }
            if (end >= srcList.get(endMid)) {
                endLeft = endMid;
            } else {
                endRight = endMid;
            }
        }
        long beginLeftDiff = Math.abs(srcList.get(beginLeft) - begin);
        long beginRightDiff = Math.abs(srcList.get(beginRight) - begin);
        long endLeftDiff = Math.abs(srcList.get(endLeft) - end);
        long endRightDiff = Math.abs(srcList.get(endRight) - end);
        int left = beginLeftDiff <= beginRightDiff ? beginLeft : beginRight;
        int right = endLeftDiff <= endRightDiff ? endLeft : endRight;
        return new Pair<>(left, right);
    }

测试函数:

@Test
    public void lemon4() {
        List<Integer> srcList = new ArrayList<>();
        Collections.addAll(srcList, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20);
        Pair<Integer, Integer> ret = Binary_search(srcList, 14, 16);
        List<Integer> retList = srcList.subList(ret.getKey(), ret.getValue() + 1);
        System.out.println(retList);
    }

参考链接:
本算法参考的算法

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值