public static void main(String[] args) {
int[] array = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38};
int k = binarySerach(array, 2);
System.out.println(" **** " + k);
}
/**
* 二分查找润樱,找到該值在數(shù)組中的下標(biāo)鸭轮,否則為-1
*/
static int binarySerach(int[] array, int key) {
int left = 0;
int right = array.length - 1;
// 這里必須是 <=
while (left <= right) {
int mid = (left + right) / 2;
System.out.println("left=" + left + " right=" + right + " 長度=" + (left + right));
System.out.println("分割值 " + mid);
if (array[mid] == key) {
return mid;
} else if (array[mid] < key) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}