Sub topic 9
Computing the Midpoint Safely
This chapter assumes you can already write the iterative binary search from earlier chapters, that you know the difference between the inclusive range [lo, hi] and the half-open range [lo, hi), and that you can read basic Java and Python. The chapter covers one line of the algorithm, the line that picks mid. That line has shipped with a bug in widely used libraries, and the bug is easy to miss when you only test small inputs.
The line that looks harmless
Every binary search computes a midpoint between two indices. The obvious way to write it is:
int mid = (low + high) / 2;In mathematics, this is always correct. In a language with fixed-width integers, it is correct only while low + high fits in the integer type. A Java int is a 32-bit signed integer. Its largest value is Integer.MAX_VALUE, which is 2,147,483,647 (2^31 − 1). When a sum goes past that, the result wraps around to a large negative number. Java does not throw an exception when this happens.
Both indices are valid, so each is at most Integer.MAX_VALUE. Their sum can still exceed it. Once the sum wraps, mid becomes negative, and a[mid] throws ArrayIndexOutOfBoundsException. In languages without bounds checks, the program reads memory outside the array instead.
Seeing the overflow
This complete program shows the wrapped result next to two correct alternatives:
public class Midpoint {
public static void main(String[] args) {
int lo = 1_500_000_000;
int hi = 2_000_000_000;
System.out.println((lo + hi) / 2); // -397483648 (wrong)
System.out.println(lo + (hi - lo) / 2); // 1750000000 (correct)
System.out.println((lo + hi) >>> 1); // 1750000000 (correct)
}
}The true sum is 3,500,000,000. Subtracting 2^32 (4,294,967,296) gives −794,967,296. Dividing that by 2 gives the negative value printed on the first line.
This bug was real
In 2006, Joshua Bloch reported that java.util.Arrays.binarySearch contained exactly this line. The code had been in the JDK for about nine years. The same bug appears in the binary search in Jon Bentley's Programming Pearls, which many programmers learned from. Nobody noticed for so long because the bug needs low + high > 2^31 − 1, so the array must hold more than about 2^30 (roughly 1.07 billion) elements. An int[] that size takes about 4 GB. In the 1990s almost no program had an array that large. By 2006 servers did.
The safe formulas
Offset from the low end
The standard fix computes the distance between the bounds and adds half of it to low:
int mid = low + (high - low) / 2;When 0 <= low <= high, the difference high - low is a non-negative number no larger than high, so it cannot overflow. Half of it, added to low, lands between low and high, so that sum cannot overflow either. The result equals floor((low + high) / 2), the same value the naive formula gives when it does not overflow. You can swap it into existing code without changing behavior.
Unsigned shift in Java
The JDK's fix was a different line:
int mid = (low + high) >>> 1;The sum still overflows. However, two non-negative ints add up to at most 2^32 − 2, and that value fits in 32 bits when the bits are read as unsigned. The >>> operator shifts right and fills the top bit with zero, so it treats the bit pattern as unsigned. The result is the correct midpoint. This trick depends on both operands being non-negative. It is fine for array indices and wrong for general integers, as the next section shows.
Using a wider type
You can also do the arithmetic in a larger type:
int mid = (int) (((long) low + high) / 2);This is clear and correct for any two int values. It is the best choice when the bounds can be negative, which happens in binary search over an answer range.
Rounding: floor and ceiling midpoints
Some loops need the midpoint rounded up instead of down. The integer square root search from the Topic Spine uses mid = (lo + hi + 1) // 2. Rounding up stops the loop from getting stuck when it sets lo = mid and lo and hi are adjacent.
The overflow-safe version of a rounded-up midpoint needs care. The obvious rewrite is:
int mid = lo + (hi - lo + 1) / 2;It overflows when hi - lo is already Integer.MAX_VALUE, for example lo = 0 and hi = Integer.MAX_VALUE. That is exactly the range an answer search over all non-negative ints uses. A version that cannot overflow subtracts from the high end:
int mid = hi - (hi - lo) / 2;This returns ceil((lo + hi) / 2). With lo = 2, hi = 3 it gives 3 - 0 = 3, which is the upper of the two candidates, as required.
| Purpose | Naive form | Overflow-safe form | Safe when |
|---|---|---|---|
| Floor midpoint | `(lo + hi) / 2` | `lo + (hi - lo) / 2` | `hi - lo` fits in the type |
| Floor midpoint, Java indices | `(lo + hi) / 2` | `(lo + hi) >>> 1` | `lo, hi >= 0` |
| Ceiling midpoint | `(lo + hi + 1) / 2` | `hi - (hi - lo) / 2` | `hi - lo` fits in the type |
| Any bounds, any sign | `(lo + hi) / 2` | `(int)(((long) lo + hi) / 2)` | values fit in `int` |
Negative bounds and division rounding
Array indices are never negative, but answer ranges can be. Negative bounds bring in two more problems.
The first problem is that Java's / truncates toward zero, while Python's // rounds toward negative infinity. These give different answers for a negative odd sum. The second problem is that >>> gives nonsense when the sum is negative.
public class NegativeMid {
public static void main(String[] args) {
int lo = -3, hi = 0;
System.out.println((lo + hi) / 2); // -1 (truncates -1.5 toward zero)
System.out.println(lo + (hi - lo) / 2); // -2 (floor, because hi - lo >= 0)
System.out.println((lo + hi) >>> 1); // 2147483646 (wrong)
}
}The form lo + (hi - lo) / 2 always rounds down, because it only divides the non-negative value hi - lo. It therefore matches Python's (lo + hi) // 2. If your loop relies on floor rounding and the bounds can go negative, (lo + hi) / 2 in Java gives a value that rounds the wrong way. That can cause an infinite loop even when no overflow happens.
The offset form has a limit of its own. If lo = -2_000_000_000 and hi = 2_000_000_000, then hi - lo is 4 billion, which overflows int. For ranges that span both signs and most of the int range, compute in long.
What about Python?
Python's built-in int has arbitrary precision. It grows as large as needed, so (lo + hi) // 2 never overflows, and the Python examples elsewhere in this tutorial are correct as written. Python code is still exposed in two cases. The first is NumPy fixed-width types, which wrap around like Java's int. The second is code that is later ported to Java, C, C++, Go, or Rust.
import numpy as np
lo = np.int32(1_500_000_000)
hi = np.int32(2_000_000_000)
print((lo + hi) // 2) # -397483648, with a RuntimeWarning about overflow
print(lo + (hi - lo) // 2) # 1750000000A corrected binary search
Here is the full iterative search with the safe midpoint, plus a small test harness:
public class SafeBinarySearch {
static int binarySearch(int[] a, int target) {
int low = 0;
int 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) {
int[] a = {1, 3, 5, 7, 9, 11};
System.out.println(binarySearch(a, 7)); // 3
System.out.println(binarySearch(a, 4)); // -1
System.out.println(binarySearch(new int[0], 4)); // -1
}
}The safe formula changes only one line, so it costs nothing in speed. Write it this way by habit, even when you expect the arrays to stay small. Code tends to outlive the assumptions it was written under.
Exercise
In Java, with lo = 0 and hi = Integer.MAX_VALUE, what does lo + (hi - lo + 1) / 2 evaluate to, and what overflow-safe expression gives the intended rounded-up midpoint?
Show answer
hi - lo + 1 is 2^31, which overflows to Integer.MIN_VALUE (-2147483648). Dividing by 2 gives -1073741824, and adding lo = 0 leaves mid = -1073741824, a negative and therefore wrong midpoint. The expression hi - (hi - lo) / 2 gives 2147483647 - 1073741823 = 1073741824, which is the correct ceiling of (0 + 2147483647) / 2.
Exercise
A Java answer-range search uses lo = -10 and hi = -5 and needs a floor midpoint. Compare (lo + hi) / 2, lo + (hi - lo) / 2, and (lo + hi) >>> 1. Which are correct?
Show answer
The true midpoint is -7.5, so the floor is -8. (lo + hi) / 2 = -15 / 2 = -7, because Java truncates toward zero, so it is wrong for a floor-based loop. lo + (hi - lo) / 2 = -10 + 5 / 2 = -10 + 2 = -8, which is correct. (lo + hi) >>> 1 treats the bits of -15 as unsigned and gives 2147483640, which is wrong. Only lo + (hi - lo) / 2 is correct here.
Exercise
Why did the (low + high) / 2 bug in java.util.Arrays.binarySearch go unnoticed for years, and what array length is needed to trigger it?
Show answer
The sum low + high exceeds Integer.MAX_VALUE (2^31 - 1) only when the indices are very large. That requires an array of more than about 2^30, roughly 1.07 billion, elements, which for an int[] is around 4 GB. Arrays that large were rare when the code was written, so ordinary tests never reached the overflow.