二分查找源代码(Java)
package sort;
public class serach {
public static int serach(int[] arr,int key,int start,int end) {
int mid = start+(end-start)/2;
if(start>end) {
return -1;
}
if(key==arr[mid]) {
return mid;
}else if(key<arr[mid]) {
serach(arr,key,start,mid-1);
}else if(key>arr[mid]) {
serach(arr,key,mid+1,end);
}
return -1;
}
public static void main(String[] args) {
int arr[]= {1,2,3,4,5,6,7,8,9};
int a = serach(arr,5,0,arr.length);
System.out.println("5的位置为"+a);
}
}
网友评论