java二分法查找

public class BinarySearch {

public BinarySearch() {
super();
}

/**
* Java二分法查找
* @param a
* @param key
* @return
*/
public static int binarySearch(int[] a, int key) {
if(a.length==0)
return -1;
//开始位置
int first = 0;
//结束位置
int last = a.length-1;
//中间位置
int mid;
//如果开始时,小于则结束.
while(first<=last)
{
mid = (first+last)/2;
//如果等于key,返回这个数在数组中的位置.
if(a[mid]==key)
return mid;
//如果大于key,则在左边.
if(a[mid]>key)
last = mid-1;
//如果小于key,则在右边
if(a[mid]<key)
first = mid+1;
}
return -1;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a={1,3,4,5,8,7,9,11,15};
System.out.println(binarySearch(a,9));
}

}

原文地址:https://www.cnblogs.com/jianming-chan/p/3273579.html