两种方法,没做异常判断
public static void main(String[] args) {
int[] array ={2,3,4,6,7,8,9,12,17,22};
System.out.println("结果"+bsearchWithoutRecursion(array,17));
}
1.while循环判断
static int test1(int a[], int key) {
int low = 0;
int high = a.length - 1;
int mid = 0;
while (low <= high){
mid = low + (high - low)/2;
if(a[mid] < key){
low = mid + 1;
}else if(a[mid] > key){
high = mid - 1;
}else{
return mid;
}
}
return -1;
}
2.递归算法
static int test2(int a[],int low,int high,int key){
int mid = low + (high - low)/2;
if(a[mid] < key){
return bas(a,mid + 1,high,key);
}else if(a[mid] > key){
return bas(a,low,mid - 1,key);
}else{
return mid;
}
}