Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A binary search in a legacy library fails for arrays with more than about a billion elements. The midpoint line is int mid = (low + high) / 2;. What is wrong and how do you fix it?

When the array has more than about a billion elements, low + high can exceed Integer.MAX_VALUE, wrap around to a negative number, and produce a negative midpoint, which throws ArrayIndexOutOfBoundsException or loops wrongly. We fix it with int mid = low + (high - low) / 2, or with (low + high) >>> 1, which treats the overflowed sum as an unsigned 32-bit number and divides it correctly. The bug sat for years in many textbook and library implementations, including the JDK's own binary search, because tests rarely use arrays that large.

Why this question is asked

This question is famous because the broken line looks like the textbook definition of a midpoint and was copied into countless programs. It shows how an overflow can hide in code that has been correct for every input anyone tried. Interviewers ask it to see whether we can spot overflow in a sum, know the two standard fixes and why the second one works, and think about how tests could have caught it. In this answer, we will recap binary search, reproduce the failure with real numbers, look at both fixes, and then talk about testing for this kind of bug.

1A Quick Recap of Binary Search

Binary search finds a value in a sorted array by repeatedly halving the range that could contain it. It keeps two indexes, low and high, looks at the element in the middle, and then throws away the half that cannot contain the value. An array of a billion elements needs only about 30 steps.

Java
static int search(int[] a, int key) {
int low = 0, high = a.length - 1;
while (low <= high) {
int mid = (low + high) / 2; // the line in question
if (a[mid] < key) low = mid + 1;
else if (a[mid] > key) high = mid - 1;
else return mid;
}
return -(low + 1); // not found
}

2Reproducing the Failure

The midpoint formula is mathematically correct. The problem is that the intermediate sum low + high is computed in int, and int tops out at 2,147,483,647. That only matters when both indexes are large, which requires an array of more than about 2^30, roughly 1.07 billion, elements.

Java
int low = 1_500_000_000;
int high = 1_600_000_000;
int sum = low + high; // -1194967296: 3,100,000,000 wrapped around
int mid = (low + high) / 2; // -597483648
// a[mid] -> ArrayIndexOutOfBoundsException: Index -597483648 out of bounds
Midpoint for low = 1.5 billion, high = 1.6 billion
FormulaIntermediate valuemidCorrect?
(low + high) / 2sum wraps to -1194967296-597483648no
low + (high - low) / 2high - low = 1000000001550000000yes
(low + high) >>> 1same wrapped bits, read as unsigned1550000000yes

When the search key lies in the upper part of a huge array, low climbs past a billion while high is still near the end, and their sum passes the int maximum. The sum wraps to a negative number, the division keeps it negative, and the array access throws. In languages without bounds checks, the same bug reads from the wrong memory instead.

3Fix 1: low + (high - low) / 2

The first fix avoids the large sum altogether. high - low is the size of the remaining range, which is never larger than the array length, so it always fits in an int. Half of it added to low lands exactly in the middle, and the result is never above high.

Java
int mid = low + (high - low) / 2; // 1550000000

This version is easy to read and works the same way in any language, which is why it is often recommended in style guides.

4Fix 2: (low + high) >>> 1

The second fix keeps the sum but changes how it is divided. The sum of two non-negative ints is at most 2^32 - 2, which always fits in 32 bits if we read those bits as an unsigned number. Overflow only made Java read the top bit as a sign. The unsigned right shift >>> shifts in a zero at the top instead of copying the sign bit, so shifting right by one divides the unsigned value by two and produces the correct, positive midpoint.

Java
int sum = low + high; // -1194967296 as a signed int
System.out.println(Integer.toUnsignedString(sum)); // 3100000000: the bits are still right
int mid = (low + high) >>> 1; // 1550000000
int wrongMid = (low + high) >> 1; // -597483648: >> keeps the sign bit

This is the form the JDK uses in Arrays.binarySearch today. It is slightly shorter and just as fast, but it relies on both indexes being non-negative, which is always true for array indexes.

5Why the Bug Lasted So Long and How to Test for It

Arrays of over a billion elements were rare when these implementations were written, and an int[] of that size needs more than 4 GB of heap, so ordinary unit tests never got close. The broken formula was in many textbooks and libraries, including the JDK's own binary search, until it was widely publicised and fixed in the mid-2000s. The lesson is that a proof of an algorithm assumes mathematical integers, while the code runs on 32-bit ones.

We can test for it without allocating huge arrays. Extract the midpoint calculation into a small method and test it directly with boundary values such as low = Integer.MAX_VALUE - 1 and high = Integer.MAX_VALUE. Property-based testing tools, such as jqwik for JUnit, can generate random pairs of non-negative ints with low <= high and check that mid always lies between them, which finds the overflow within a few runs.

Java
@Property
void midIsBetween(@ForAll @IntRange(min = 0) int a, @ForAll @IntRange(min = 0) int b) {
int low = Math.min(a, b), high = Math.max(a, b);
int mid = Search.mid(low, high);
assertTrue(low <= mid && mid <= high); // fails for (low + high) / 2 with large values
}

6Follow-up questions

Does the same bug affect other algorithms?

Yes, anywhere two large indexes or sizes are added: merge sort's midpoint, computing the end of a buffer as offset + length, or comparing offset + length > size, which can overflow and pass the check. Writing such checks as length > size - offset avoids the overflow.

Could we just use long for the indexes?

We could compute mid as (int) (((long) low + high) / 2), which is also correct. But Java array indexes are int anyway, so the two standard fixes are simpler and avoid the conversions.

Why not use Math.addExact for the sum?

It would turn the silent bug into an exception, which is better than a wrong answer, but the search would still fail for large arrays. The goal here is a correct midpoint for every valid input, which both fixes give us without any exception.

7Conclusion

In this answer, we saw that (low + high) / 2 overflows when the array has more than about 2^30 elements, because the sum of two large indexes exceeds Integer.MAX_VALUE and wraps to a negative value. low + (high - low) / 2 avoids the large sum, and (low + high) >>> 1 reads the overflowed bits as unsigned and halves them correctly. The bug survived for years in widely used code, including the JDK, because tests never used arrays that large; testing the midpoint function directly with boundary and property-based tests finds it quickly.

What to say in the interviewAbout 90 seconds aloud

Open with

The problem is integer overflow in low + high. The midpoint formula is correct in mathematics, but the sum is computed in a 32-bit int. Once the array has more than about 2 to the 30 elements, roughly a billion, both indexes can be large, and their sum can exceed Integer.MAX_VALUE.

Then, if they want more

For example, low of 1.5 billion and high of 1.6 billion add up to 3.1 billion, which wraps to about minus 1.19 billion, so mid becomes negative and the array access throws an index out of bounds exception. There are two standard fixes.

One is low + (high - low) / 2: the difference is never bigger than the array, so it always fits, and adding half of it to low gives the midpoint. The other is (low + high) >>> 1.

The sum of two non-negative ints always fits in 32 bits as an unsigned number, overflow only flipped the sign bit, and the unsigned shift brings a zero in at the top, so it halves the unsigned value correctly. That is what the JDK's Arrays.binarySearch uses now; the JDK itself had the broken version for years before it was fixed.

I would also point out why it survived: unit tests never use arrays that large. I would test the midpoint function directly with values near Integer.MAX_VALUE, or with a property-based test that checks low <= mid <= high.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A binary search in a legacy library fails for arrays with more than about a billion...": https://scrivio-interview-library.netlify.app/java/types-and-values/a0f2a6fa12/