Binary Search

Find a number in a sorted array by checking the middle and throwing away the half that cannot hold it.

Given an array of integers nums sorted in ascending order and an integer target, return the index of target in nums, or -1 if it is not in the array. The search must run in O(log n) time: for an array of n numbers, the number of steps may grow only with the logarithm of n, not with n itself.

Example 1
Input: nums = [-1, 0, 3, 5, 9, 12], target = 9
Output: 4
Example 2
Input: nums = [-1, 0, 3, 5, 9, 12], target = 2
Output: -1
Solution

The Idea

Think of looking up a word in a paper dictionary. You do not read it from the first page. You open it near the middle, see whether your word comes before or after that page, and keep only that half. A handful of such openings finds any word in a thick book.

The array in the examples can be searched the same way, because it is sorted. Take Example 2: is 2 in [-1, 0, 3, 5, 9, 12]? Reading from the left compares 2 with -1, 0 and 3 before it is clear that 2 is missing. On an array of a million numbers, such a scan can take a million comparisons. Can the sorted order tell us more from a single comparison?

It can. Compare 2 with a number in the middle, 3 at index 2. Since 3 is bigger than 2, and every number to its right is bigger still, 2 can only be to the left of index 2. That one comparison has ruled out four of the six numbers.

The part of the array that can still hold the target is called the range. Two indexes mark it: lo for its first position and hi for its last. The position halfway between them is mid. Look at the picture below, which follows the search for 2 one row per comparison.

Searching for 2 in -1, 0, 3, 5, 9, 12. Row 1: lo = 0, hi = 5, mid on 3, so hi = 1. Row 2: mid on -1, so lo = 1. Row 3: mid on 0, so lo = 2. Row 4: lo = 2 is past hi = 1, the range is empty, return -1.

In the first row, lo = 0 and hi = 5, and mid lands on 3. Since 3 > 2, hi moves to 1, and in the second row the numbers from 3 onwards are grey: they are out of the range. There mid lands on -1, which is smaller than 2, so lo moves to 1. In the third row only 0 is left, and 0 < 2 moves lo to 2.

In the last row, lo = 2 has passed hi = 1. Nothing is left to check, so 2 is not in the array and the answer is -1.

So each comparison throws away about half of what is left. Six numbers need at most three comparisons, and a million numbers need at most 20. Splitting the range in two at every step is what gives binary search its name.

Solution Approach

Turning that idea into code means settling four things: what lo and hi mark, how they move, when the search stops, and how to compute mid safely.

The range between lo and hi

Should hi mark the last position that is still possible, or the one after it? Both work, as long as the code sticks to one choice. Here both ends count: if the target is anywhere, it is at an index from lo to hi, including lo and hi themselves. The search starts with the whole array, lo = 0 and hi = nums.length - 1.

Moving lo and hi

After comparing nums[mid] with target, where do lo and hi go? If nums[mid] is smaller, the target can only be to the right of mid, so lo becomes mid + 1. If it is bigger, hi becomes mid - 1. Both skip mid, which was just compared, so the range loses at least one number on every pass and the loop cannot get stuck.

When to stop

When does the search give up? Not when lo and hi meet. With lo == hi the range still holds one number, as in the third row of the picture, and that number must be compared too. The range is empty only once lo has passed hi, so the loop runs while lo <= hi.

Finding the middle without overflow

The obvious way to compute mid is (lo + hi) / 2. Indexes are Java int values, and the largest int is 2,147,483,647, about 2.1 billion. In an array of more than a billion numbers, lo + hi can go past that and wrap around to a negative value, which is called overflow. Writing lo + (hi - lo) / 2 gives the same middle, and hi - lo never gets that big.

Java Solution

The method search works in these steps:

  1. First, set lo to 0 and hi to nums.length - 1, so the range covers the whole array.
  2. Start a loop that runs while lo <= hi, that is, while the range still holds a number. Inside it, compute mid as lo + (hi - lo) / 2.
  3. If nums[mid] equals target, return mid.
  4. If nums[mid] is smaller than target, move lo to mid + 1. Otherwise it is bigger, so move hi to mid - 1.
  5. If the loop ends, the range is empty and the target is not in the array, so return -1.

The main method runs both examples, then searches for the last number, 12, and for -5, which is smaller than every number. It also searches a one-number array and an empty one, and prints both ways of computing the middle of 1,500,000,000 and 2,000,000,000.

Java
public class BinarySearch {

    public static int search(int[] nums, int target) {
        int lo = 0;
        int hi = nums.length - 1;            // the target, if present, is in nums[lo..hi]
        while (lo <= hi) {                   // stop when the range is empty
            int mid = lo + (hi - lo) / 2;    // no overflow, unlike (lo + hi) / 2
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                lo = mid + 1;                // target can only be to the right of mid
            } else {
                hi = mid - 1;                // target can only be to the left of mid
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] nums = {-1, 0, 3, 5, 9, 12};
        System.out.println(search(nums, 9));
        System.out.println(search(nums, 2));
        System.out.println(search(nums, 12));
        System.out.println(search(nums, -5));
        System.out.println(search(new int[] {5}, 5));
        System.out.println(search(new int[] {}, 5));
        int lo = 1500000000;
        int hi = 2000000000;
        System.out.println((lo + hi) / 2 + " " + (lo + (hi - lo) / 2));
    }
}

Running it prints:

Output
4
-1
5
-1
0
-1
-397483648 1750000000

The 4 and -1 at the top answer the two examples. The 5 below them is the search for 12: the range shrinks until only index 5 is left, and that last number is still compared. Searching for -5 prints -1, because every comparison moves hi left until it drops below lo.

The 0 on the fifth line comes from [5], where the loop runs once with lo and hi both 0. With while (lo < hi) instead, that loop would never run and the line would print -1, and so would the search for 12. The empty array prints -1 because hi starts at -1 and the loop never runs.

The last line shows the overflow. (lo + hi) / 2 gives -397483648, a negative index, while lo + (hi - lo) / 2 gives 1750000000, the true middle.

The original implementation, BinarySearch.java, is on GitHub. In everyday Java code, Arrays.binarySearch(nums, target) searches the same way. When the target is missing it returns a negative number that tells where the target would go, not always -1: for 2 in the example array it returns -3.

Complexity

The work is the number of passes of the loop, and each pass costs one comparison and a few index updates.

  • Time: O(log n), because each pass at least halves the range of n numbers, so the loop runs at most about log2(n) + 1 times. An array of a million numbers needs at most 20 passes.
  • Space: O(1), because the search keeps only lo, hi and mid, makes no copy of the array and calls nothing recursively.

Variations of this loop solve many other problems; Binary Search Basics explains the two templates and when to use each.