java实现 二分查找 非递归与递归2种方式
非递归,利用循环
package file;
import java.util.Scanner;
public class Main {
public static void search(int[] a,int key){
int low=0;
int high=a.length-1;
int mid;
while(low<=high){
mid=(low+high)/2;
if(a[mid]==key){
System.out.println(mid);
return;
}
else if(a[mid]>key){
high=mid-1;
}
else{
low=mid+1;
}
}
return;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
System.out.println("输入数组长度:");
int len=in.nextInt();
System.out.println("输入数组:");
int[] a=new int[len];
for(int i=0;i<len;i++){
a[i]=in.nextInt();
}
System.out.println("输入key:");
int key=in.nextInt();
search(a,key);
}
}
递归方法
package file;
import java.util.Scanner;
public class Main {
public static int search(int[] a,int key,int start,int end){
if(start>end)
return -1;
int mid=(start+end)/2;
if(a[mid]==key){
System.out.println(mid);
return mid;
}
else if(a[mid]>key){
return search(a,key,start,mid-1);
}
else{
return search(a,key,mid+1,end);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
System.out.println("输入数组长度:");
int len=in.nextInt();
System.out.println("输入数组:");
int[] a=new int[len];
for(int i=0;i<len;i++){
a[i]=in.nextInt();
}
System.out.println("输入key:");
int key=in.nextInt();
System.out.println(search(a,key,0,len-1));
}
}