package test;
public class Search {
//非递归方式
private static int binarySearch(int [] a,int x){
int begin = 0;
int end = a.length-1;
while(begin <= end){
int middle = (begin+end)/2;
if(x == a[middle]){
return middle;
}
if(x > a[middle]){
begin = middle+1;
}
if(x < a[middle]){
end = middle-1;
}
}
return -1;
}
//递归方式
private static int binSearch(int [] a,int x,int begin,int end){
int middle = (begin + end)/2;
if(end > begin){
return -1;
}
if(x == a[middle]){
return middle;
}else if(x > a[middle]){
return binSearch(a,x,middle+1,end);
}else if(x < a[middle]){
return binSearch(a,x,begin,middle-1);
}
return -1;
}
/**
* <p>方法名称: main|描述: </p>
* @param args
*/
public static void main(String[] args) {
int a [] = {1,5,12,45,67,99,120};
System.out.println(binarySearch(a,-2));
System.out.println(binSearch(a,-2,0,a.length-1));
}
}
二分查找算法
最新推荐文章于 2023-08-23 16:38:52 发布