在一个有序的数组中,折半查找一个元素key,如果能找到返回数组的下表,如果找不到,返回-1。
实现如下所示:
/**
* 二分查找法
* @author jcm
* 2016年8月6日
*/
public class BinarySerach {
public static void main(String[] args) {
int a[] = {13,19,32,35,56,75,97,98,112,332,789};
int flag = binarySearch(a,19);
if (flag == -1)
System.out.println("没有找到元素值");
else
System.out.println("在数组的第"+flag+"处找到元素,值是"+a[flag]);
}
private static int binarySearch(int a[],int key){
int low=0;
int high = a.length-1;
int mid;
while(low<=high){
mid = (low+high)/2;
System.out.print("最低位是"+low+" 最高位是"+high+" 中间位置是"+mid);
System.out.println();
if (key == a[mid])
return mid;
else if (key>a[mid])
low = mid +1;
else
high = mid-1;
}
return -1;
}
}