分别使用迭代和递归的方式来实现
public class binarySearch {
/**
* 使用迭代的方式
* @param a
* @param num
* @return
*/
public static int search(int a[],int num){
if(a==null||a.length==0){
return -1;
}
int left =0;
int right=a.length-1;
while (left<=right){
int middle = left+((right-left)>>1);
if(num == a[middle]){
return middle;
}
if(num > a[middle]){
left = middle+1;
}else {
right = middle-1;
}
}
return -1;
}
public static int search(int a[],int num,int left,int right){
if(num == a[left]){
return left;
}
if(num == a[right]){
return right;
}
int middle = left+((right-left)>>1);
if(left!=right){
if(num > a[middle]){
return search(a,num,middle+1,right);
}else {
return search(a,num,left,middle);
}
}
return -1;
}
public static void main(String[] args) {
int []a={1,2,3,4,5,6,7,8,9,10,34,55,66,77,88,100};
//System.out.println(search(a,63));
System.out.println(search(a,4,0,a.length-1));
}
}