二分法查找:当数据量很大适宜采用该方法。采用二分法查找时,数据需是排好序的。
二分查找时间复杂度 O(logn)
/**
* 二分法查找,数据需要有序不重复
*/
public class DichotomySearch {
public static void main(String[] args) {
int[] arr = {11,22,33,44,55,66,77,88,99};
System.out.println("88 = " + search(arr, 88)); //7
System.out.println("44 = " + search(arr, 44)); //3
System.out.println("100 = " + search(arr, 100));//-1
}
//二分法查找
public static int search(int[] arr, int key){
int start = 0;
int end = arr.length - 1;
while(start <= end){
int middle = (start + end) / 2;
if(key < arr[middle]){
end = middle - 1;
}else if(key > arr[middle]){
start = middle + 1;
}else{
return middle;
}
}
return -1;
}
}