数组是从大到小排好序的,以下是代码
public class BinarySearch {
public static void main(String[] args) {
int a[]={2,4,7,9,10,14,17,19};
int index=binarySearch(a, 19);
System.out.println(""+index);
}
public static int binarySearch(int array[],int value){
int low=0;
int high=array.length-1;
while(low<=high){
int mid=(low+high)/2;
if(value<array[mid])
high=mid-1;
else if(value>array[mid]){
low=mid+1;
}else{
return mid;
}
}
return -1;
}
}
重点是while循环 必须是low<=high,有的文章把等号漏掉了,导致查找不出来!
当然while循环也可以使用递归代替,有兴趣的朋友可以试试,这里就不赘述了!
参考博客:http://www.cnblogs.com/qqzy168/archive/2013/08/03/3219201.html