数据结构-查找
时间:2019-11-01 21:16:34
收藏:0
阅读:99
一、二分查找
必须为有序数组
1.1递归实现
static int recursive(int[] arr,int low,int high,int target){
if(target < arr[low] || target >arr[high] || low> high){
return -1;
}
int middle = (low + high)/2;
if(arr[middle] <target){
return recursive(arr, middle+1, high, target);
}else if(arr[middle]>target){
return recursive(arr,0,middle-1, target);
}
else{
return middle;
}
}
1.2 循环实现
public static void main(String[] args) {
Arrays.sort(array);
int num = 1;
int end = array.length-1,begin=0;
while(array[(begin + end)/2] != num){
if(num < array[(begin + end)/2]){
end = (begin + end)/2;
}
else{
begin=(begin + end)/2;
}
}
System.out.println((begin + end)/2);
}
原文:https://www.cnblogs.com/mushuise/p/11779087.html
评论(0)