public class ZheBan {
public static void main(String[] args) {
int[] arr = {1,3,5,8,10,15,46};
System.out.println(getIndex(arr, 10));
}
/*
* 折半排序
*/
public static int getIndex(int[] arr,int key){
int max = arr.length-1,min = 0,mid;
while (min <= max) {
mid = (min + max) / 2;
if (key > arr[mid]) {
min = mid + 1;
}else if (key < arr[mid]) {
max = mid -1;
}else{
return mid;
}
}
return min;
}
} |