二分查找法-JAVA源码
程序员文章站
2024-03-16 09:00:40
...
以下是java.util.arrays,java源码的二分查找实现,使用的是循环,而不是递归,更好理解。
private static int binarySearch(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.
}