/*二分查找
*
*/
public class Testsearch {
public static void main(String[] args) {
int[] intArray = { 1, 3, 5, 7, 9, 88 };
int key = 2;
System.out.println("key的索引值为" + binarySearch(intArray, key));
}
public static int binarySearch(int[] intArray, int key) {
// 定义数组的上下界low,high和分半后的mid
int low = 0;
int high = intArray.length - 1;
int mid = (low + high) / 2;
// 当数组下标为mid的值不是key时,进入while
while (intArray[mid] != key) {
// 数组分为左右两部分
if (intArray[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
mid = (low + high) / 2;
// 数组中没有key,查找失败,返回-1
if (low > high) {
return -1;
}
}
return mid;
}
}