二分法查找:
从排序好的数组,找到你需要找到的值(t=1),算法复杂度:O(log n)
步骤:首先确认查找的数组索引范围,
1:假设数据int[] arr = {0,1,2,3,4,5,6,7,8,9};
2:则搜索范围为 [0,9];即int start =0;int end = 9;
3:取数组索引中间的值跟t比较,int middle = (start + end)/2=4;
4:如果arr[middle]>t;则搜索范围控制在了(0,middle-1],即 end = middle-1;
相反,arr[middle]<t;则搜索范围控制在(middle+1,9],则 start = middle+1;
5:如果arr[middle]=t,搜索结束,否则就重复3,4。
/**
* 二分法
*/
public void testBinarySearch(){
int[] arr = {1,2,3,4,5,6,7,8};
int t = -1;
System.out.println(binary_search(arr,t));
}
//二分法搜索算法
private Integer binary_search(int[] arr, int t) {
int start = 0, end = arr.length - 1;//扫描范围
while (start<=end){
int mid = (end + start) / 2;//中间数索引位置
if (t< arr[mid]){
end = mid-1;
}
if (t>arr[mid]){
start = mid+1;
}
if (t == arr[mid]){
return mid;
}
}
return null;
}