1
uselessVisitor 2021-04-15 20:45:44 +08:00
这不就是二分查找吗?百度一下都有
|
2
uselessVisitor 2021-04-15 21:04:17 +08:00
public static int binarySearch(int[] arrays, int key, int start, int end) {
if (key < arrays[start] || key > arrays[end] || start > end) { return -1; } int mid = (start + end) / 2; if (arrays[mid] > key) { return binarySearch(arrays, key, start, mid - 1); } else if (arrays[mid] < key) { return binarySearch(arrays, key, mid + 1, end); } else { return mid; } } |
3
uselessVisitor 2021-04-15 21:06:32 +08:00
jdk 的写法
// Like public version, but without range checks. private static int binarySearch0(int[] a, int fromIndex, int toIndex, int key) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; int midVal = a[mid]; if (midVal < key) low = mid + 1; else if (midVal > key) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. } |
4
KissFace OP @beichenhpy 谢谢老哥
|