##利用二分查找法查找数组中的连续的一段数据(前提数组有序)
最近在做一个项目,向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);
}
参考链接:
本算法参考的算法