public class 折半查找 {
public static void main(String[] args) {
int arr[] ={1,2,5,6,8,9,90};
int index = getIndex(arr,9);
System.out.println(index);
}
public static int getIndex(int arr[] , int key){
int max=arr.length-1;
int min=0;
int mid;
while(max>=min){
mid=(max+min)>>1;
if(key>arr[mid]){
min=mid+1;
}
else if(key<arr[mid]){
max=mid-1;
}
else{
return mid;
}
}
return max;
}
}
|
|