//用二分法查找一个数再数组中的索引值,前提数组必须是有序的
public static void main(String[] args) {
int []arr = { 18, 37, 54, 76, 92};
int midIndex= getIndex(arr,76);
System.out.println(midIndex);
}
public static int getIndex(int []arr,int value){
int maxIndex =arr.length -1 ;
int minIndex = 0;
int midIndex = (maxIndex+minIndex)/2 ;
while(arr[midIndex]!=value){
if (arr[midIndex]>value) {
maxIndex= midIndex -1;
}else if (arr[midIndex]<value) {
minIndex =midIndex+1;
}
if (minIndex>maxIndex) {
return -1;
}
midIndex= (maxIndex+minIndex)/2 ;
}
return midIndex;
}
------------------------------------ |
|