下面展示一些 二分查找实现代码
。
// 二分查找法——折半查找
public class ArrErFenChaZhao {
public static void main(String[] args){
int[] arr5 = {1,2,20,45,88,154,456};
// 以20来查找比较
System.out.println(twoPointsSearch(arr5,20));
}
public static int twoPointsSearch(int[] arr5,int key ){
int min =0;
int max=arr5.length - 1;
int mid = 0;
while(min <= max){
mid=( min + max )/2;
if(key > arr5[mid]){
min = mid + 1;
}
if( key < arr5[mid] ){
max = mid-1;
}
if( key == arr5[mid] ){
return mid;
}
}
return -1;
}
}