二分查找算法的非递归调用与递归调用实现:
/**
* 非递归 调用
*/
private static int search1(int[] array,int key){
int low = 0;
int high = array.length - 1;
while(low <= high){
int mid = (low + high) >> 1;
if(key == array[mid]){
return mid;
}else if(key < array[mid]){
high = mid - 1;
}else{
low = mid + 1;
}
}
return -1;
}
/**
* 二分查找法 递归调用
*/
private static int search2(int[] array,int key){
int low = 0;
int high = array.length - 1;
return recursion(array,key,low,high);
}
private static int recursion(int[] array,int key,int low,int high){
if(low > high){
return -1;
}
int mid = (low + high) >> 1;
if(key == array[mid]){
return mid;
}else if(key < array[mid]){
return recursion(array,key,low,mid-1);
}else{
return recursion(array,key,mid+1,high);
}
}
参考链接:
https://blog.csdn.net/qq_42378705/article/details/105127049