public class BinarySearch {
public static void main(String[] args) {
int[] nums = {12,14,18,23,34,45,55,67};
int subScript = binarySearch(nums,23);
if (subScript!=-1){
System.out.println("查询数据的下标为:" + subScript);
}else {
System.out.println("查无此数据!");
}
}
public static int binarySearch(int[] num,int key){
int start = 0;
int end = num.length-1;
while (start<=end){
int mid = (start+end)/2;
if (key>num[mid]){
start=mid+1;
}else if (key<num[mid]){
end=mid-1;
}else{
return mid;
}
}
return -1;
}
}
运行结果: