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; } }
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. }