一、需求
在有序数组内,查找值target。如果找到返回索引,如果找不到返回-1。
二、算法思想
二分查找又叫折半查找,要求待查找的序列有序。每次取中间位置的值与待查值比较,
如果中间位置的值比待查值大,则在前半部分循环这个查找的过程,
如果中间位置的值比待查值小,则在后半部分循环这个查找的过程。
直到查找到了为止,否则序列中没有待查的值。
三、使用两种方式实现
public class BinarySearch {
private int[] arrays;
public BinarySearch(int[] arrays) {
this.arrays = Arrays.stream(arrays)
.sorted()
.toArray();
}
/**
* 二分查找平衡版
* 1.左闭右开的区间,start指向的可能是目标,而end指向的不是目标
* 2.不在循环内找出,等范围内只剩i时,退出循环,在循环外比较a[i]与target
* 3.循环内的平均比较次数减少了
* 4。时间复杂度Θ(log(n))
* @param target
* @return 查找到的索引,没找到则返回-1
*/
public int binarySearchByBalance(int target) {
int start=0,end=arrays.length;
while(1<end - start){
int mid=(end +start)>>>1;//无符号右移,避免超过int最大值
if(target<arrays[mid]){
end = mid;
}else {
star