Java 二分法查询
使用场景:数据量大,有序不可重复的查询
package com.datastruct.search;
/**
* 有序数组
* 时间复查度O(log2n,即以2为底n的对数)
*/
public class BinarySearch{
public static void main(String[] args) {
int[] mm = {1,5,9,10,25,36};
System.out.println(binarySearch(mm,24));
}
public static int binarySearch(int[] arr,int searchValue){
//默认数组第一个元素项
int lowerBound = 0;
//数组最后一个元素项
int upperBound = arr.length-1;
//数组中间元素项
int curtIndex;
//每循环一次,范围缩小一半
while (true){
curtIndex = (lowerBound+upperBound)/2;
if (arr[curtIndex]==searchValue){
return curtIndex;
}else if(lowerBound>upperBound){
return -1;//未找到
}else{
if (arr[curtIndex]<searchValue){
//数组后半部分查询,改变最小下标
lowerBound = curtIndex+1;
}else{
//数组前半部分查询,改变最大下标
upperBound = curtIndex-1;
}
}
}
}
}