Sub topic 9
Computing the Midpoint Safely
This chapter assumes you have read the iterative binary search chapter. You should know what int means in Java and roughly how many values a 32-bit integer can hold. The topic is one line of code: the line that computes mid. In some languages, the obvious way to write it is wrong.
The Bug in `(low + high) / 2`
In Java, C, C++, and C#, an int is a fixed-width 32-bit signed integer. Its largest value is 2,147,483,647, which is Integer.MAX_VALUE in Java. A sum larger than that does not grow. It wraps around to a negative number.
Binary search only ever computes mid from two valid indexes, so the result itself always fits in an int. The intermediate sum low + high might not. Suppose an array has about two billion elements and the search has narrowed to its upper half:
public class MidpointOverflow {
public static void main(String[] args) {
int low = 1_500_000_000;
int high = 2_000_000_000;
int naive = (low + high) / 2;
int safe = low + (high - low) / 2;
int shifted = (low + high) >>> 1;
System.out.println(naive); // -397483648
System.out.println(safe); // 1750000000
System.out.println(shifted); // 1750000000
}
}The true sum is 3,500,000,000. After wrapping it becomes -794,967,296, and halving that gives a negative "midpoint". Using it as an array index throws ArrayIndexOutOfBoundsException. In C and C++, signed overflow is undefined behavior, so the program may crash or quietly read the wrong memory.
This bug is not hypothetical. Java's own Arrays.binarySearch used (low + high) / 2 for years. Joshua Bloch reported the problem publicly in 2006, after arrays large enough to trigger it became common.
The Safe Forms
The fix is to avoid adding two large numbers together. high - low is the size of the remaining range. It is never negative and never larger than the array length, so it always fits. Adding half of it to low gives the same midpoint without the overflow.
| Expression | Overflow-safe? | Notes |
|---|---|---|
| `(low + high) / 2` | No | Fails when the sum exceeds `Integer.MAX_VALUE` |
| `low + (high - low) / 2` | Yes | Works in every fixed-width language; the usual choice |
| `(low + high) >>> 1` | Yes, in Java | The unsigned shift treats the wrapped sum as unsigned; needs `low` and `high` to be non-negative |
Here is the full search with the safe form:
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;
}Both forms round down, so low + (high - low) / 2 gives exactly the same mid as the naive version whenever the naive version doesn't overflow. You can swap one for the other without changing any loop invariant or boundary logic.
Rounding Up Safely
Some variants need the midpoint rounded up so the loop doesn't get stuck when low and high are adjacent. The safe version is low + (high - low + 1) / 2. Rounding up and rounding down are both covered again in later chapters on bound variants and searching over an answer range.
Exercise
In Java, with low = 2,000,000,000 and high = 2,100,000,000, what does (low + high) / 2 evaluate to, and what does low + (high - low) / 2 evaluate to?
Show answer
The true sum, 4,100,000,000, wraps to 4,100,000,000 - 4,294,967,296 = -194,967,296, and halving gives -97,483,648. The safe form gives 2,000,000,000 + 100,000,000 / 2 = 2,050,000,000, which is the correct midpoint.
Exercise
Why can high - low never overflow inside a correct binary search loop?
Show answer
Inside the loop, 0 <= low <= high <= a.length - 1. The difference is therefore between 0 and a.length - 1, and that value always fits in an int because the array length is itself an int.