二分查找与递归式二分查找

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/SilentWu/article/details/79758087

二分查找

public class BinarySearch{

public static void main(String[] args) {
int[] arr = {1,3,2,5,6,4,7,9,8};
Arrays.sort(arr);
// TODO Auto-generated method stub
int low = 0;
int high = arr.length-1;
while(low<=high){
int mid = (low+high)/2;
if(arr[mid]==5){
System.out.println("True");
return;
}else{
if(arr[mid]<5){
low = mid+1;
}else{
high = mid-1;
}
}
}

}

}

递归实现二分查找

public class RecursiveQuery1{

        public static void f(int[] aa,int bottom,int top,int num){

int mid = (bottom+top)/2;
if(top>=bottom){
if(aa[mid]==num){//设置递归出口
System.out.println("True");
return;
}else{
if(aa[mid]<5){
f(aa,mid+1,top,num);//若当前的aa[mid]小于5那么要到右边区域中去查找 并让bottom = mid+1
}else{
f(aa,bottom,mid-1,num);//若当前的aa[mid]大于5则到左边区域中去查找 并让high = mid-1
}
}
  }
}
public static void main(String[] args) {
int[] arr = {1,3,2,5,6,4,7,9,8};
Arrays.sort(arr);//在使用二分查找前 需要对数组进行排序
// TODO Auto-generated method stub
int low = 0;
int high = arr.length-1;
f(arr,low,high,5);//查找5是否在这个数组中 
}

}

当要查询的数据量特别多时,二分查找比普通的顺序查找的效率要高的多。

猜你喜欢

转载自blog.csdn.net/SilentWu/article/details/79758087