Binary search
Binary search finds a value in a sorted sequence by repeatedly halving the range it could be in. It takes O(log n) comparisons instead of the O(n) a linear scan needs.
Detailed Explanation
Looking for a name in a sorted list of a million entries by checking each one takes a million comparisons in the worst case. Binary search takes twenty. That gap is why it is the first optimisation anyone learns.
The idea is the one you use on a physical dictionary. Open in the middle. If the word you want sorts before the page you landed on, the whole right half is irrelevant and you never look at it again. Repeat on what is left. Each step throws away half the remaining candidates, so n shrinks to 1 after about log2(n) steps.
The invariant is what makes it correct: at the top of every loop iteration, if the target is present at all, its index lies inside [low, high]. Every branch must preserve that. When array[mid] < target, the target cannot be at mid or anywhere to its left, so low = mid + 1 is safe. When array[mid] > target, high = mid - 1 is safe. Setting low = mid instead of mid + 1 keeps a candidate that has already been ruled out and produces an infinite loop.
The precondition is absolute: the data must be sorted by the same ordering the search uses. Binary search on unsorted input does not throw. It returns a wrong answer quietly, which is much worse.
Compute the midpoint as low + (high - low) / 2, not (low + high) / 2. The second version adds two int values that can sum past Integer.MAX_VALUE and wrap negative, and a negative index throws ArrayIndexOutOfBoundsException. This bug sat in the JDK's own Arrays.binarySearch until 2006, so it is not a hypothetical.
The JDK gives you Arrays.binarySearch for arrays and Collections.binarySearch for lists, both with comparator overloads. Their return value has a useful twist. A match returns its index. A miss returns -(insertionPoint) - 1, a negative number encoding where the value would go. Recover the insertion point with -result - 1. That makes one call serve both "find it" and "where would it go".
One caveat on Collections.binarySearch: on a list that does not implement RandomAccess, such as LinkedList, it still performs O(log n) comparisons but walks the list with an iterator, so the total work is O(n).
The variant worth learning beside plain search is lower bound: the first index whose value is greater than or equal to the target. It handles duplicates deterministically, answers range-counting questions, and is what TreeMap.ceilingKey does for you on a sorted map.
Interview problems that are binary search in disguise: Search in Rotated Sorted Array, Find First and Last Position, Median of Two Sorted Arrays, Koko Eating Bananas and Capacity to Ship Packages, where you binary search over an answer range rather than an array. Time is O(log n), space is O(1) when written iteratively.
Code Examples
public class BinarySearch {
// Returns an index of target, or -1 when it is absent. Input must be sorted.
static int search(int[] sorted, int target) {
int low = 0;
int high = sorted.length - 1; // inclusive upper bound
// Invariant: if target exists, its index is somewhere in [low, high].
while (low <= high) {
// Not (low + high) / 2: that sum can overflow int on a large array.
int mid = low + (high - low) / 2;
if (sorted[mid] == target) {
return mid;
} else if (sorted[mid] < target) {
low = mid + 1; // mid is too small, so discard it and everything left
} else {
high = mid - 1; // mid is too large, so discard it and everything right
}
}
return -1;
}
// First index whose value is >= target, or sorted.length if there is none.
static int lowerBound(int[] sorted, int target) {
int low = 0;
int high = sorted.length; // exclusive this time, so length is a valid answer
while (low < high) {
int mid = low + (high - low) / 2;
if (sorted[mid] < target) {
low = mid + 1;
} else {
high = mid; // mid itself might be the answer, so keep it in range
}
}
return low;
}
public static void main(String[] args) {
int[] data = {2, 4, 4, 4, 8, 16, 23, 42};
System.out.println(search(data, 23)); // prints: 6
System.out.println(search(data, 5)); // prints: -1
System.out.println(lowerBound(data, 4)); // prints: 1
System.out.println(lowerBound(data, 5)); // prints: 4
System.out.println(lowerBound(data, 99)); // prints: 8
}
}import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class JdkBinarySearch {
public static void main(String[] args) {
int[] data = {2, 4, 8, 16};
System.out.println(Arrays.binarySearch(data, 8)); // prints: 2
// A miss returns -(insertion point) - 1, which is always negative.
int result = Arrays.binarySearch(data, 5);
System.out.println(result); // prints: -3
System.out.println(-result - 1); // prints: 2, the index where 5 would belong
List<String> names = List.of("ana", "bo", "cy");
System.out.println(Collections.binarySearch(names, "bo")); // prints: 1
}
}Common Gotchas
`(low + high) / 2` overflows
on arrays with more than about a billion elements the sum wraps negative and the next array access throws `ArrayIndexOutOfBoundsException`. Always write `low + (high - low) / 2`.
Unsorted input fails silently
the method returns a plausible-looking index or `-1` with no error. If a list is sorted with one comparator and searched with another, you get the same silent wrongness. The search comparator must match the sort comparator exactly.
A negative return value is data, not failure
`Arrays.binarySearch` encodes the insertion point in the negative result. Testing `if (index >= 0)` is the correct presence check; testing `if (index != -1)` is wrong, because a miss can return any negative number.
With duplicates the JDK picks an arbitrary match
`Arrays.binarySearch` guarantees nothing about which equal element it lands on. When you need the first or last occurrence, write the lower-bound variant yourself.