算法设计技巧与分析p104页算法6.2,思想就不说了,注意一些细节就可以了
public class BINARYSEARCH6_2 {
public static int search(int a[],int element,int low,int high){
if(high>=low){
int mid=(low+high)/2;
if(a[mid]==element){
return mid;
}
else{
int t1=search(a,element,low,mid-1);//这里一定是mid-1否则会进入死循环
if(t1!=-1)
return t1;
else{
return search(a,element,mid+1,high);
}
}
}
else{
return -1;
}
}
public static void main(String args[]){
int[] a={5,7,9,6,8,0,9};
int element=9;
System.out.println(search(a,element,0,5));
}
}