二分查找
public class arithmetic {
public static void main(String[] args) {
int [] arr={1,2,5,7,9,13,16};
int result = binarySerach(9, arr);
System.out.println("结果:"+result);
}
public static int binarySerach(int ref, int [] a){
int low=0;
int high=a.length-1;
int mid=0;
//low<=high,不加等号就会漏数据
while(low<=high){
mid=(low+high)/2;
if (ref==a[mid]) {
return mid; //返回查询结果
}else if (ref<a[mid]) {//查询左半块数据
high=mid-1;
}else{//查询右半块数据
low=mid+1;
}
}
// 没有查询到,输出-1
return -1;
}
}
浙公网安备 33010602011771号