满足二分查找法,首先你的数据需要是有顺序的
基本上原理就是,一段倾斜的路上找到想要的高度,先直接在路的中间找,如果高度高于想要的高度,然后就将起点和中等高度的位置当成新的一段路.然后重复上面的操作,
public class BinarySearch {
public static void main(String args[]) {
int[] arr = {16, 31, 33, 57, 92, 197, 228, 561};
// 非递归版本
System.out.println(binarySearch(arr, 90));
// 递归版
System.out.println(binarySearch(arr, 90, 0, arr.length - 1));
}
// 递归版
private static int binarySearch(int[] arr, int x, int low, int hight) {
int middle = (low + hight) / 2;
if (x < arr[low] || x > arr[hight] || low > hight) {
return -1;
}
if (arr[middle] == x) {
return middle;
} else {
if (arr[middle] < x) {
return binarySearch(arr, x, ++middle, hight);
} else {
return binarySearch(arr, x, low, --hight);
}
}
}
// 非递归版本
private static int binarySearch(int[] arr, int x) {
int low = 0;
int hight = arr.length - 1;
while (low <= hight) {
int middle = (low + hight) / 2;
if (arr[middle] == x) {
return middle;
} else {
if (arr[middle] < x) {
low = middle + 1;
} else {
hight = middle - 1;
}
}
}
// 查找不到
return -1;
}
}