一.递归实现
public class Binarys {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6,7,8,9,10,50,60,67,88,99,555,4444};
int a = binary(arr,4,0,arr.length-1);
System.out.println(a);
}
//二分查找,参数:有序数组,查找数,起始位置,结束位置
public static int binary(int[] arr,int key,int low,int high) {
if( key<arr[low] || key>arr[high] || low>high )
return -1;
int middle = (low+high)/2;
if(key>arr[middle]) {
return binary(arr, key , middle,high);
}else if(key<arr[middle]){
return binary(arr, key , low,middle);
}else {
return middle;
}
}
}
网友评论