先给数据排序(例如按升序排好),形成有序表,
然后再将key与正中元素相比,若key小,则缩小至右半部内查找;
再取其中值比较,每次缩小1/2的范围,直到查找成功或失败为止。
public class Arrayutil {
public static void main(String[] args) {
int[] a = {1,2,3,4,5,6,7};
binarySearch( a,1);
}
public static boolean binarySearch(int[] a, int key) {
int high = a.length-1;
int low = 0;
int mid = (high + low)/2;
while (high >= low){
if (a[mid] == key){
System.out.println("元素以找到,下标是:"+mid);
return true;
}else if (a[mid]>key){
high = mid - 1;
mid = (high + low)/2;
}else if (a[mid] < key){
low = mid +1;
mid = (high + low)/2;
}
}
System.out.println("元素未找到");
return false;
}
}