Classic binary search in Java
28 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Donald Knuth famously observed that although the first binary search was published in 1946, the first bug-free binary search for all array sizes was not published until 1962—and Java's own Arrays.binarySearch had a hidden integer-overflow bug for nine years until 2006! Mastering the exact loop condition, safe midpoint formula, and library return convention prevents every one of those bugs.
lo, hi and the loop condition
In classic binary search, we define both lo and hi as inclusive bounds ([lo .. hi]): initially lo = 0 and hi = arr.length - 1.
Why must the loop condition be while (lo <= hi) instead of while (lo < hi)? Consider a 1-element range where lo == hi (for example, arr = {42} with lo = 0, hi = 0, or when a larger search narrows down to a single remaining candidate). When lo == hi, the interval [lo .. hi] still contains 1 unchecked element! Using lo < hi would exit the loop before testing that final element.
The loop only terminates when lo > hi (specifically lo == hi + 1), meaning the search interval [lo .. hi] is genuinely empty.
lo = 0, hi = n - 1: closed interval[lo, hi]withhi - lo + 1candidates.while (lo <= hi): continues as long as at least 1 candidate remains.lo = mid + 1orhi = mid - 1: strictly decreaseshi - loon every iteration, guaranteeing termination.
Binary Search for target = 23 in [2, 5, 8, 12, 16, 23, 38, 56, 72]
Step 1 of 3
- lo
- 0
- mid
- 4
- hi
- 8
- arr[mid]
- 16
- target
- 23
A safe mid: lo + (hi − lo) / 2
In school algebra, the average of lo and hi is (lo + hi) / 2. Why is int mid = (lo + hi) / 2; a notorious bug in Java?
Example 1 · Why (lo + hi) / 2 overflows and lo + (hi - lo) / 2 stays safe
public class SafeMidDemo { public static void main(String[] args) { int lo = 1_500_000_000; int hi = 1_600_000_000;
int buggyMid = (lo + hi) / 2; int safeMid = lo + (hi - lo) / 2; int shiftMid = (lo + hi) >>> 1;
System.out.println("buggyMid = " + buggyMid); System.out.println("safeMid = " + safeMid); System.out.println("shiftMid = " + shiftMid); }}buggyMid = -597483648 safeMid = 1550000000 shiftMid = 1550000000
What this code does
- lo + hi equals 3,100,000,000, which wraps around Integer.MAX_VALUE (2,147,483,647) to -1,194,967,296; dividing by 2 gives -597,483,648.
- Both lo + (hi - lo) / 2 and (lo + hi) >>> 1 produce the true midpoint 1,550,000,000.
int mid = lo + (hi - lo) / 2;— subtracts first (hi - locannot overflow when0 <= lo <= hi), then adds half the distance tolo. Works for bothintandlong.int mid = (lo + hi) >>> 1;— uses Java's unsigned right-shift operator>>> 1, which shifts the 32nd sign/carry bit back into bit 30. This is whatjava.util.Arrays.binarySearchuses since Java 6.
In Java, int has a maximum value of Integer.MAX_VALUE (2³¹ - 1 = 2,147,483,647). If you search a large array or answer space where lo = 1_500_000_000 and hi = 1_600_000_000, their sum lo + hi is 3,100,000,000, which overflows 32-bit signed int into a negative number (-1,194,967,296), making (lo + hi) / 2 negative and throwing ArrayIndexOutOfBoundsException! Two overflow-safe formulas exist for non-negative lo <= hi:
Find the bug
Spot the binary search bug
Each method has one wrong line. Tap the line to fix, then check.
Middle of a very large range of ids.
Round 1 of 3lo + (hi - lo) / 2 in interviews and production code—it is crystal clear and works even when lo and hi are signed negative integers (as long as hi - lo fits in the type).Iterative versus recursive
You can write binary search either iteratively with a while (lo <= hi) loop or recursively with a helper binarySearch(arr, target, lo, hi).
- Iterative binary search: O(log n) time, O(1) auxiliary space.
- Recursive binary search: O(log n) time, O(log n) call-stack space.
Example 2 · Iterative vs recursive binary search side by side
public class IterativeVsRecursiveDemo { public static int searchIterative(int[] arr, int target) { int lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (arr[mid] == target) return mid; if (arr[mid] < target) lo = mid + 1; else hi = mid - 1; } return -1; }
public static int searchRecursive(int[] arr, int target, int lo, int hi) { if (lo > hi) return -1; int mid = lo + (hi - lo) / 2; if (arr[mid] == target) return mid; if (arr[mid] < target) return searchRecursive(arr, target, mid + 1, hi); return searchRecursive(arr, target, lo, mid - 1); }
public static void main(String[] args) { int[] arr = {3, 8, 15, 23, 42, 56}; System.out.println(searchIterative(arr, 23) + " " + searchRecursive(arr, 23, 0, arr.length - 1)); System.out.println(searchIterative(arr, 10) + " " + searchRecursive(arr, 10, 0, arr.length - 1)); }}3 3 -1 -1
What this code does
- In the recursive version, the base case lo > hi corresponds to the while (lo <= hi) loop exit condition.
- Both return 3 when searching for 23 and -1 when searching for 10.
Both perform the exact same comparisons and run in O(log n) time. However, Java does not perform tail-call optimization: each recursive call pushes a stack frame onto the call stack, using O(log n) auxiliary stack space, whereas the iterative loop uses O(1) extra space and avoids method-call overhead. Prefer the iterative version.
Arrays.binarySearch and its negative result
Java's standard library provides Arrays.binarySearch(arr, key) (and Collections.binarySearch(list, key)). What does it return when key is not found?
Example 3 · Decoding Arrays.binarySearch negative insertion points
import java.util.Arrays;
public class ArraysBinarySearchDemo { public static void main(String[] args) { int[] nums = {10, 20, 30, 40}; int[] queries = {20, 5, 25, 50};
for (int q : queries) { int res = Arrays.binarySearch(nums, q); if (res >= 0) { System.out.println("Query " + q + ": found at index " + res); } else { int insertPos = -res - 1; System.out.println("Query " + q + ": absent (raw=" + res + "), insert at " + insertPos); } } }}Query 20: found at index 1 Query 5: absent (raw=-1), insert at 0 Query 25: absent (raw=-3), insert at 2 Query 50: absent (raw=-5), insert at 4
What this code does
- For query 5 (smaller than all elements), insertionPoint is 0, so Arrays.binarySearch returns -(0) - 1 = -1.
- Recovering -res - 1 (or ~res) gives 0 for 5, 2 for 25, and 4 for 50.
- If
idx >= 0:keywas found at indexidx(if duplicates exist,Arrays.binarySearchdoes not guarantee which duplicate index is returned). - If
idx < 0:keyis absent, andint insertPos = -idx - 1;(equivalently~idx) is the exact sorted insertion index in0 .. arr.length.
Simply returning -1 would throw away valuable information: where key would belong in sorted order! And returning -insertionPoint directly would be ambiguous when insertionPoint == 0 because -0 is 0 (indistinguishable from finding key at index 0). Therefore, Arrays.binarySearch returns -(insertionPoint) - 1, where insertionPoint is the index of the first element greater than key (or arr.length if all elements are smaller). When the return value idx < 0, you recover insertionPoint with -idx - 1 (or bitwise ~idx)!
Next step
Check your understanding
10 quick questions