二分查找
public static int binarySearch(int[] array, int key) {
int low = 0, high = array.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (array[mid] > key) {
high = mid - 1;
} else if (array[mid] < key) {
low = mid + 1;
} else {
return mid;
}
}
return -1;
}
public static int binarySearch(int[] array, int key, int low, int high) {
int mid = (low + high) / 2;
if (array[mid] > key) {
high = mid - 1;
if (low > high) {
return -1;
}
return binarySearch(array, key, low, high);
} else if (array[mid] < key) {
low = mid + 1;
if (low > high) {
return -1;
}
return binarySearch(array, key, low, high);
} else {
return mid;
}
}