Binary Search Basics

How cutting a sorted range in half finds a value, a boundary, or the smallest answer that works, with Java templates.

When you look for page 300 in a thick book, you do not turn the pages one by one. You open it somewhere near the middle, read the page number, and know at once which half to keep. Then you do the same with that half.

Binary search is that habit written as code. It works on anything kept in order, such as a sorted array or a range of possible answers. It finds a value, the place where something starts to be true, or the smallest answer that is good enough, while looking at only a few positions.

Halving a sorted range

Take a sorted array of eight numbers, nums = [2, 4, 7, 7, 7, 9, 11, 14], and ask where 11 is. The same eight numbers carry every idea that follows.

Searching for 11 in 2, 4, 7, 7, 7, 9, 11, 14. Step 1: range 0 to 7, middle index 3 holds 7, so index 0 to 3 is dropped. Step 2: range 4 to 7, middle index 5 holds 9, so index 4 and 5 are dropped. Step 3: middle index 6 holds 11, found.

Look at the row labelled Step 1. At the start, 11 could be anywhere from index 0 to index 7. The middle of that range is index 3, drawn in orange, and it holds 7.

Since 7 is smaller than 11 and the array is sorted, every number at index 0 to 3 is 7 or less. None of them can be 11, so all four are dropped at once. They turn grey in the row labelled Step 2.

Step 2 repeats the move on the range 4 to 7. Its middle, index 5, holds 9, which is still smaller than 11, so index 4 and 5 go too. In Step 3 the middle of the range 6 to 7 is index 6, and it holds 11.

Three looks were enough, and each one threw away about half of what was left. The name "binary" comes from that split in two at every step.

Notice what made the drop safe: the order. In a shuffled array, seeing 7 at index 3 says nothing about index 0 to 2, and no half could be thrown away.

What halving saves

How much work does the simple way take? Reading nums from the left until 11 turns up takes seven comparisons, one for each of 2, 4, 7, 7, 7, 9 and 11. For a number that is not in the array, it reads all eight.

The number of looks for halving grows far more slowly. With 8 numbers, the search never needs more than 4 looks. A program that searched every value in a sorted array of 1,000,000 numbers, plus missing values, never needed more than 20 looks.

The reason is that each look halves the range. Starting from 1,000,000 numbers, twenty halvings bring the range down to a single number, because 220 = 1,048,576. In general the count is about log2 n for n numbers, which is written O(log n): the work grows like log n.

Finding one exact value

How do you write the halving down precisely? The code has a fixed shape that carries over from problem to problem, so it is worth learning as a template. The first template keeps two indexes, lo and hi. They mark the part of the array where the target might still be, both ends included.

  • Start with lo = 0 and hi = n - 1, the whole array.
  • While lo <= hi, the range still holds at least one number. Look at the middle index, mid.
  • If nums[mid] is the target, return mid.
  • If nums[mid] is smaller, the target can only be to the right, so lo = mid + 1.
  • If it is larger, the target can only be to the left, so hi = mid - 1.
  • When lo passes hi, the range is empty and the target is not in the array.

Both updates step past mid, because mid has just been checked. That is what makes the range shrink every round.

Now search for 8, which is missing. The middle of 0 to 7 is index 3, holding 7, so lo becomes 4. The middle of 4 to 7 is index 5, holding 9, so hi becomes 4. The range 4 to 4 holds 7, so lo becomes 5.

Now lo = 5 and hi = 4, the loop stops, and the answer is "not found". There is a bonus, too: lo stopped at 5, exactly where 8 would have to be inserted to keep the array sorted.

What about 7, which appears three times? The very first look lands on index 3, which holds a 7, and the search returns 3. That is a correct answer to "where is a 7?", but not to "where is the first 7?". That second question needs a different template.

Finding where a condition starts

Many questions are not "where is x?" but "where does something begin?". Where do the 7s start? Where is the first number bigger than 7? Turn each into a yes-or-no question about every index, and look at the answers in a row.

The array 2, 4, 7, 7, 7, 9, 11, 14 with two rows of answers. Value at least 7: no, no, then yes from index 2 on, so the first yes is index 2. Value greater than 7: no up to index 4, then yes, so the first yes is index 5. 5 minus 2 is 3 copies of 7.

Look at the row labelled "value ≥ 7?". Because the array is sorted, the answers are all "no" first and all "yes" after, and they switch exactly once. The first yes is at index 2, marked in orange. That is where the 7s start.

The row labelled "value > 7?" switches later, at index 5 in teal. Every index from 2 up to 4 holds a 7, so the array has 5 - 2 = 3 copies of 7.

Any test whose answers run "no, no, ..., yes, yes" like these rows is called monotone. The second template finds the first yes for any monotone test. It keeps two indexes, left and right, and the first yes always lies somewhere from left to right.

  • Start with left on the first index and right one past the last index. The position past the end stands for "no index says yes".
  • While left < right, test the middle index mid.
  • If mid says yes, the first yes is mid or earlier, so right = mid. Here mid is kept, because it may be the answer.
  • If mid says no, the first yes is after it, so left = mid + 1.
  • When left meets right, they point at the first yes.

On the row "value ≥ 7?", left = 0 and right = 8. Index 4 says yes, so right becomes 4. Index 2 says yes, so right becomes 2. Index 1 says no, so left becomes 2, and the two meet at index 2.

There is no "found it" exit here. The loop always runs until the range closes, so the answer is the first yes even when several positions say yes. If no index says yes, as for "value ≥ 15?", the answer is 8, one past the end.

Searching over possible answers

Binary search does not need an array to look into. It needs a range of candidates and a monotone yes-or-no test. Here is a question with no array to search, built from the same eight numbers.

Treat [2, 4, 7, 7, 7, 9, 11, 14] as the weights of packages that must be shipped in this order. A truck carries at most some capacity per day, and a package that does not fit waits for the next day. What is the smallest capacity that ships everything within 3 days?

The capacity cannot be below 14, or the heaviest package never fits. It never needs to be above 61, the total of all weights, which ships everything in one day. So the answer lies in 14 to 61.

Now ask "does capacity c ship everything in 3 days?". If some capacity works, every bigger one works too, since a bigger truck never needs more days. So the answers run no, ..., no, yes, ..., yes, and the second template applies.

Capacities 14 to 61 on a line. Below 25 the packages do not ship in 3 days, from 25 up they do. The tries, in order: 38 yes, 26 yes, 20 no, 23 no, 25 yes, 24 no. The search settles on 25.

Look at the boxes labelled "the tries, in order". The search first tries 38, the middle of 14 to 61, and it works. Then 26 works too. Then 20 and 23 are too small, and 25 works while 24 does not. So 25 is the smallest capacity, found with six tries.

Check 25 by hand. Day one takes 2, 4, 7 and 7, which is 20, and the next 7 would make 27. Day two takes 7 and 9, which is 16. Day three takes 11 and 14, exactly 25.

The slow way tries 14, 15, 16 and so on until one works. That is 12 tries here, each one a full pass over the packages, and up to 48 if the answer were 61.

The templates in Java

In the program below, the first template is the method exactSearch. The second is firstTrue, which takes its yes-or-no test as an IntPredicate, a Java interface for a test on one int. The test for the row "value ≥ 7?" is then the lambda, a short inline function, i -> nums[i] >= 7.

For the packages, daysNeeded loads the weights in order and starts a new day whenever the next one does not fit. Then smallestCapacity calls firstTrue over 14 to 61 with the test "daysNeeded is at most the allowed days".

The program's main method repeats every search walked through so far. It adds an empty array, the first and last numbers, a value past the end, 1 day and 8 days for the packages, and Java's own Arrays.binarySearch.

Java
import java.util.Arrays;
import java.util.function.IntPredicate;

public class BinarySearchBasics {

    // Template 1: the index of target in the sorted array nums, or -1 if it is not there.
    static int exactSearch(int[] nums, int target) {
        int lo = 0;
        int hi = nums.length - 1;              // target, if present, is in [lo, hi]
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                lo = mid + 1;                  // target can only be right of mid
            } else {
                hi = mid - 1;                  // target can only be left of mid
            }
        }
        return -1;
    }

    // Template 2: the smallest x in [lo, hi] with ok(x) true, or hi + 1 if there is none.
    // ok must answer false, ..., false, true, ..., true as x grows.
    static int firstTrue(int lo, int hi, IntPredicate ok) {
        int left = lo;
        int right = hi + 1;                    // hi + 1 stands for "never true"
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (ok.test(mid)) {
                right = mid;                   // the first true is mid or earlier
            } else {
                left = mid + 1;                // the first true is after mid
            }
        }
        return left;
    }

    // How many days it takes to ship the weights in order, at most capacity per day.
    static int daysNeeded(int[] weights, int capacity) {
        int days = 1;
        int load = 0;
        for (int w : weights) {
            if (load + w > capacity) {
                days++;
                load = 0;
            }
            load += w;
        }
        return days;
    }

    static int smallestCapacity(int[] weights, int days) {
        int heaviest = Arrays.stream(weights).max().getAsInt();
        int total = Arrays.stream(weights).sum();
        return firstTrue(heaviest, total, c -> daysNeeded(weights, c) <= days);
    }

    public static void main(String[] args) {
        int[] nums = {2, 4, 7, 7, 7, 9, 11, 14};
        int n = nums.length;

        System.out.println("exactSearch 11: " + exactSearch(nums, 11));
        System.out.println("exactSearch 8:  " + exactSearch(nums, 8));
        System.out.println("exactSearch 7:  " + exactSearch(nums, 7));
        System.out.println("exactSearch 2:  " + exactSearch(nums, 2));
        System.out.println("exactSearch 14: " + exactSearch(nums, 14));
        System.out.println("empty array:    " + exactSearch(new int[0], 5));

        int first7 = firstTrue(0, n - 1, i -> nums[i] >= 7);
        int after7 = firstTrue(0, n - 1, i -> nums[i] > 7);
        System.out.println("first index with value >= 7: " + first7);
        System.out.println("first index with value > 7:  " + after7);
        System.out.println("copies of 7: " + (after7 - first7));
        int first8 = firstTrue(0, n - 1, i -> nums[i] >= 8);
        int first15 = firstTrue(0, n - 1, i -> nums[i] >= 15);
        System.out.println("first index with value >= 8:  " + first8);
        System.out.println("first index with value >= 15: " + first15);

        System.out.println("smallest capacity for 3 days: " + smallestCapacity(nums, 3));
        System.out.println("smallest capacity for 1 day:  " + smallestCapacity(nums, 1));
        System.out.println("smallest capacity for 8 days: " + smallestCapacity(nums, 8));

        System.out.println("Arrays.binarySearch 7: " + Arrays.binarySearch(nums, 7));
        System.out.println("Arrays.binarySearch 8: " + Arrays.binarySearch(nums, 8));
    }
}

Running it prints:

Output
exactSearch 11: 6
exactSearch 8:  -1
exactSearch 7:  3
exactSearch 2:  0
exactSearch 14: 7
empty array:    -1
first index with value >= 7: 2
first index with value > 7:  5
copies of 7: 3
first index with value >= 8:  5
first index with value >= 15: 8
smallest capacity for 3 days: 25
smallest capacity for 1 day:  61
smallest capacity for 8 days: 14
Arrays.binarySearch 7: 3
Arrays.binarySearch 8: -6

The line exactSearch 7: 3 is the duplicate case: the first template returns the second of the three 7s, while first index with value >= 7: 2 finds where the 7s start. The line copies of 7: 3 is the difference of the two boundaries, 5 - 2.

The line first index with value >= 8: 5 matches where the missing 8 would go, the same 5 that lo stopped at in the search for 8. The value 15 gives 8, one past the end, meaning no index qualifies.

For the packages, 3 days need capacity 25. One day needs 61, the total weight. Eight days need 14, because a truck must still carry the heaviest package alone.

Typical traps

Look at the last two output lines. Arrays.binarySearch(nums, 7) returned 3, the second of the three 7s, just like exactSearch. So with repeated values it is not a way to find the first or last copy.

For a missing value it returns a negative number, minus the insertion point minus one. For 8 that is -6, which is -(5) - 1, and 5 is again where 8 would go.

Two more traps hide in how the middle index is worked out and in how the range is updated. The program below shows both:

Java
public class Traps {

    // Last index whose value is <= limit, written with lo = mid. maxRounds stops a stuck loop.
    static String lastAtMost(int[] nums, int limit, boolean roundUp, int maxRounds) {
        int lo = 0;
        int hi = nums.length - 1;              // assumes nums[0] <= limit
        for (int round = 1; lo < hi; round++) {
            if (round > maxRounds) {
                return "stuck after " + maxRounds + " rounds, lo=" + lo + " hi=" + hi;
            }
            int mid = roundUp ? lo + (hi - lo + 1) / 2 : lo + (hi - lo) / 2;
            if (nums[mid] <= limit) {
                lo = mid;                      // mid is a candidate, keep it
            } else {
                hi = mid - 1;
            }
        }
        return "answer " + lo;
    }

    public static void main(String[] args) {
        int lo = 1200000000;
        int hi = 2000000000;
        System.out.println("(lo + hi) / 2      = " + (lo + hi) / 2);
        System.out.println("lo + (hi - lo) / 2 = " + (lo + (hi - lo) / 2));

        int[] nums = {2, 4, 7, 7, 7, 9, 11, 14};
        System.out.println("round down: " + lastAtMost(nums, 7, false, 100));
        System.out.println("round up:   " + lastAtMost(nums, 7, true, 100));
    }
}

Running it prints:

Output
(lo + hi) / 2      = -547483648
lo + (hi - lo) / 2 = 1600000000
round down: stuck after 100 rounds, lo=3 hi=4
round up:   answer 4

The first line is the overflow trap. A Java int stops at about 2.1 billion. When searching over answers, lo and hi can be 1,200,000,000 and 2,000,000,000, and their sum wraps around to a negative number. So (lo + hi) / 2 gives -547483648.

Writing the middle as lo + (hi - lo) / 2 adds half the gap to the low end instead. For two ends that are zero or more, that never overflows, and the second line shows the correct 1600000000. Both templates use this form.

The third line is the stuck-loop trap. The method lastAtMost looks for the last index whose value is at most 7. A yes keeps mid with lo = mid. With lo = 3 and hi = 4, rounding down gives mid = 3 again. Index 3 says yes, lo stays 3, and nothing changes.

The guard stopped it after 100 rounds; without one it would loop forever. Rounding the middle up, with lo + (hi - lo + 1) / 2, picks index 4 instead, and the last line shows the right answer, 4. The rule: if one branch keeps mid as the new low end, round up.

Recognising a binary search problem

How do you spot a problem that fits? Look for one of these signs:

  • The input is sorted, and the question is where a value is or where it would go.
  • The question asks for the first or last position where something holds, such as the first 7 or the first number bigger than 7.
  • The question asks for the smallest or largest value that is "good enough", and a bigger value is always at least as good, like the truck capacity.
  • The array is not fully sorted, but one look at the middle still tells you which half to keep, as in an array that was sorted and then rotated.

In each case, write the question as a yes-or-no test and check that its answers switch only once. If they do, the second template fits.

Complexity

Every binary search costs the number of looks times the cost of one look.

  • Exact search and boundary search: O(log n) time, because each look halves the range of the n indexes, and O(1) extra space, because only lo, hi and mid (or left and right) are kept.
  • Searching over answers: O(n log R) time, where R is the number of candidate answers, because each of the roughly log2 R tries runs daysNeeded over all n packages. Here R is 48, and the search needed 6 tries.

Where to go next

Finding one exact value, as in the first template:

Finding where a condition starts, as in the second template:

Arrays that are not fully sorted:

Searching over possible answers: