public class 二分查找 {
public static void main(String[] args) {
int arr[] = {1,2,3,4,990};
System.out.println(getIndex(arr,99));
}
public static int getIndex(int arr[] ,int key){
int max = arr.length-1,min= 0,mid;
while(arr[max]>=arr[min]){
mid = (max+min)/2;
if(arr[mid]>key){
max = mid-1;
}
else if(arr[mid]<key){
min = mid+1;
}
else{
return mid;
}
}
return -1;
}
} |
|