class Test13 {
public static void main(String[] args) {
int[] arr = {2,5,8,10,41};
int index = halfSearch(arr,10);
System.out.println("index=" +index);
}
public static int halfSearch(int[] arr, int key) {
int min = 0,max = arr.length-1;
while (min<=max) {
int mid= (min+max)>>1;
if (key >arr[mid]) {
min =mid+1;
} else if (key < arr[mid]) {
max=mid-1;
} else
return mid;
}
return -1;
}
}
mid是索引值,而key是数组内元素的值,所以是拿key和arr[mid]去比较 |