二分法查找
“`
public static void main(String[] args) {
int[] binary=new int[]{1,2,3,4,5,6,7,8,9};
int ret=binarySearch(binary,3);
if(ret==-1){
System.out.println(“不存在”);
}else if(ret!=-1){
System.out.println(ret);
}
}
public static int binarySearch(int[] a,int num){
int low=0;
int upper=a.length-1;
while(low<=upper){
int mid=(low+upper)/2;
if(a[mid]<num){
low=mid+1;
}else if (a[mid]>num){
upper=mid-1;
}else{
return mid;
}
}
return -1;
}
“`## Java API中的实现 ##
java.util.Arrays数组操作工具类
public static void sort(int[] a);//经过调优的快速排序方法;
public static int binarySearch(int[] a,int key);//使用二分搜索法;