Sub topic 3
Computing the Midpoint Safely
This chapter assumes you can already write iterative binary search over an inclusive range [lo, hi] and read basic Big-O notation.
Computing the Midpoint Safely
In Java or C, (low + high) / 2 can overflow once low + high is larger than the maximum int, which is about 2.1 billion. The sum wraps around to a negative number, and the array access then fails. low + (high - low) / 2 gives the same midpoint and never goes past high.
public class Search {
static int binarySearch(int[] a, int target) {
int low = 0, high = a.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (a[mid] == target) return mid;
else if (a[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}
public static void main(String[] args) {
System.out.println(binarySearch(new int[]{1, 3, 5, 7, 9}, 7)); // 3
}
}Python integers have no fixed size, so (lo + hi) // 2 is safe in Python.
Binary Search as Recursion
The recursive version makes the same comparisons, but each step is a call on the half that remains. The base case is the empty range, where lo > hi. Each call adds a stack frame, so it uses O(log n) extra memory. The loop version uses O(1).
Lower Bound, Upper Bound, and Duplicates
Lower bound searches the half-open range [lo, hi). It returns the first index whose element is at least the target. That index is also where the target would be inserted to keep the list sorted.
def lower_bound(a, target):
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2
if a[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
print(lower_bound([1, 3, 3, 3, 7], 3)) # 1Upper bound returns the first index whose element is greater than the target. You get it by changing < to <=. Upper bound minus lower bound is the number of copies of the target.
Using the Standard Library Instead of Writing Your Own
| Language | Function | Result when the target is missing |
|---|---|---|
| Python | `bisect.bisect_left` / `bisect_right` | The insertion point |
| Java | `Arrays.binarySearch` | `-(insertion point) - 1` |
The library versions are tested and handle the edge cases, so use them unless you need custom behavior.
Binary Search over an Answer Range
You can also binary search a range of candidate answers instead of an array. This works whenever a yes/no test is true for every value up to some point and false after it. For an integer square root, the test is mid * mid <= n. When the loop sets lo = mid, round the midpoint up with (lo + hi + 1) // 2. Otherwise the loop never ends once lo and hi are next to each other.
Choosing the Right Search
Sorting costs O(n log n). That cost only pays off if you search the same data many times. For a single search, or for a very small list, linear search's O(n) is cheaper.
Exercise
In Java, Arrays.binarySearch(a, 4) returns -3. Where should 4 be inserted?
Show answer
The insertion point is -(-3) - 1 = 2.
Exercise
Why does isqrt use (lo + hi + 1) // 2 instead of (lo + hi) // 2?
Show answer
When lo and hi are adjacent and the test is true, rounding down sets mid to lo. The assignment lo = mid then changes nothing, so the loop repeats forever.