Skip to lesson

How binary search works

If you look for the word "orbit" in a printed dictionary by flipping from page 1 one page at a time, you are doing a linear search. If you open the dictionary to the middle, see "mango", and immediately discard the entire first half because "orbit" comes after "mango", you are doing binary search.

Halving a sorted range

Binary search finds a target in a sorted array by checking the middle element and throwing away the half that cannot contain the target, taking O(log n) steps.

A linear search inspects elements one by one from index 0 to n - 1. If the array is unsorted, you have no choice: the target could be hiding anywhere, so in the worst case you must inspect all n elements (O(n) time).

Example 1 · Tracing range halving step by step on a sorted array

BinarySearchTraceDemo.javaJava
public class BinarySearchTraceDemo {    public static int searchWithTrace(int[] arr, int target) {        int lo = 0, hi = arr.length - 1;        int step = 1;        while (lo <= hi) {            int mid = lo + (hi - lo) / 2;            System.out.println("Step " + step + ": range [" + lo + ".." + hi                + "], mid=" + mid + " (val=" + arr[mid] + ")");            if (arr[mid] == target) {                return mid;            } else if (arr[mid] < target) {                lo = mid + 1;            } else {                hi = mid - 1;            }            step++;        }        return -1;    }
    public static void main(String[] args) {        int[] prices = {12, 18, 25, 31, 44, 52, 67, 79, 88, 95};        int idx = searchWithTrace(prices, 79);        System.out.println("Found at index: " + idx);    }}
Output
Step 1: range [0..9], mid=4 (val=44)
Step 2: range [5..9], mid=7 (val=79)
Found at index: 7

What this code does

  • On step 1, mid = 4 holds 44 < 79, so indices 0..4 are discarded at once and lo jumps to 5.
  • On step 2, the midpoint of [5..9] is index 7, which holds 79 and finishes the search in 2 steps.
  • a[mid] == target: you found the target at index mid.
  • a[mid] < target: target must lie strictly to the right of mid, so narrow the range to [mid + 1 .. hi].
  • a[mid] > target: target must lie strictly to the left of mid, so narrow the range to [lo .. mid - 1].

When the array is sorted in non-decreasing order (a[0] <= a[1] <= ... <= a[n - 1]), a single comparison in the middle tells you about half the array at once. Suppose you maintain an active search range [lo .. hi] (initially [0 .. n - 1]) and inspect the middle index mid. Three outcomes are possible: Because the array is sorted, when a[mid] < target, every element to the left of mid is also <= a[mid] < target. You can discard lo .. mid without ever looking at those elements!

Binary search requires a monotonic (sorted) order. Running binary search on an unsorted array silently misses elements that are in the wrong half.

The guess-the-number game

Imagine a friend picks a secret integer between 1 and 100, and after each guess tells you "Too low", "Too high", or "Correct!". Why is guessing 50 first always better than guessing 10?

  1. range [1 .. 100], guess mid = 50 -> Too low (50 < 73), new range [51 .. 100] (50 left).
  2. range [51 .. 100], guess mid = 75 -> Too high (75 > 73), new range [51 .. 74] (24 left).
  3. range [51 .. 74], guess mid = 62 -> Too low (62 < 73), new range [63 .. 74] (12 left).
  4. range [63 .. 74], guess mid = 68 -> Too low (68 < 73), new range [69 .. 74] (6 left).
  5. range [69 .. 74], guess mid = 71 -> Too low (71 < 73), new range [72 .. 74] (3 left).
  6. range [72 .. 74], guess mid = 73 -> Correct! Found in 6 guesses out of 100 numbers.

Example 2 · Simulating the Guess-the-Number game (1 to 100)

GuessGameDemo.javaJava
public class GuessGameDemo {    public static int playGuessGame(int n, int secret) {        int lo = 1, hi = n, guesses = 0;        while (lo <= hi) {            int mid = lo + (hi - lo) / 2;            guesses++;            if (mid == secret) {                return guesses;            } else if (mid < secret) {                lo = mid + 1;            } else {                hi = mid - 1;            }        }        return guesses;    }
    public static void main(String[] args) {        System.out.println("Secret 73 in 1..100 took: " + playGuessGame(100, 73) + " guesses");        System.out.println("Secret 1 in 1..1000000 took: " + playGuessGame(1_000_000, 1) + " guesses");    }}
Output
Secret 73 in 1..100 took: 6 guesses
Secret 1 in 1..1000000 took: 19 guesses

What this code does

  • Even when the range grows 10,000x larger (from 100 to 1,000,000), the worst-case number of guesses grows from 7 to at most 20.
  • Each guess eliminates mid itself plus roughly half of the remaining numbers.

If you guess 10 and hear "Too low", you eliminate only 10 numbers (1..10), leaving 90 possibilities (11..100). If you guess the midpoint 50, then regardless of whether your friend says "Too low" (51..100 remain) or "Too high" (1..49 remain), you eliminate at least half of the remaining candidates on every single turn. Let us hand-trace searching for target = 73 in [1 .. 100]:

Predict the output

How many checks at most?

Each loop run halves the list. Pick what each program prints.

Round 1 of 2

A sorted list has 16 ids. How many halvings until nothing is left?

public class HalvingCountA {
public static void main(String[] args) {
int n = 16;
int checks = 0;
while (n >= 1) {
n = n / 2;
checks++;
}
System.out.println(checks);
}
}

Only about log n steps

How many times can you cut an n-element range in half before at most 1 element remains? The base-2 logarithm log₂(n) counts how many times 2 multiplies to reach n.

Example 3 · Brute force: check every id one by one (O(n) time, O(1) space)

LinearScanChecks.javaJava
public class LinearScanChecks {    public static void main(String[] args) {        int[] ids = new int[1000];        for (int i = 0; i < ids.length; i++) {            ids[i] = 1000 + 3 * i;        }        int target = ids[900];        int checks = 0;        int found = -1;        for (int i = 0; i < ids.length; i++) {            checks++;            if (ids[i] == target) {                found = i;                break;            }        }        System.out.println("Found at index " + found + " after " + checks + " checks");    }}
Output
Found at index 900 after 901 checks

What this code does

  • The scan reaches index 900 after 901 checks; for a million ids it could need a million checks.
  • It is slow because it ignores the sorted order: every check throws away only one id.

Example 4 · Optimal: halve the id range each time (O(log n) time, O(1) space)

HalvingChecks.javaJava
public class HalvingChecks {    public static void main(String[] args) {        int[] ids = new int[1000];        for (int i = 0; i < ids.length; i++) {            ids[i] = 1000 + 3 * i;        }        int target = ids[900];        int lo = 0, hi = ids.length - 1;        int checks = 0;        int found = -1;        while (lo <= hi) {            int mid = lo + (hi - lo) / 2;            checks++;            if (ids[mid] == target) {                found = mid;                break;            } else if (ids[mid] < target) {                lo = mid + 1;            } else {                hi = mid - 1;            }        }        System.out.println("Found at index " + found + " after " + checks + " checks");    }}
Output
Found at index 900 after 10 checks

What this code does

  • Each check discards half of the remaining ids, so the same search needs only 10 checks (about log₂ 1000).
  • Doubling the list adds just one more check, which is why a billion sorted ids need at most about 30.

Example 5 · Worst-case step count formula: floor(log2(n)) + 1

MaxStepsFormulaDemo.javaJava
public class MaxStepsFormulaDemo {    public static int maxBinarySearchSteps(long n) {        int steps = 0;        while (n > 0) {            n /= 2;            steps++;        }        return steps;    }
    public static void main(String[] args) {        long[] sizes = {10L, 1_000L, 1_000_000L, 1_000_000_000L};        for (long n : sizes) {            System.out.println("n=" + n + " -> max steps=" + maxBinarySearchSteps(n));        }    }}
Output
n=10 -> max steps=4
n=1000 -> max steps=10
n=1000000 -> max steps=20
n=1000000000 -> max steps=30

What this code does

  • Because each comparison shrinks a range of length n to at most floor((n - 1) / 2) elements, the loop can run at most floor(log2(n)) + 1 times.
  • For 1 billion sorted items, 30 comparisons suffice even when the target is not in the array.

Specifically, a range of size n takes at most ⌊ log₂(n) ⌋ + 1 comparisons in the worst case. Because each extra comparison doubles the size of the array you can search, binary search scales almost effortlessly to massive datasets:

  • n = 1,000 (10³): linear search takes up to 1,000 steps; binary search takes at most 10 steps (2¹⁰ = 1,024).
  • n = 1,000,000 (10⁶): linear search takes up to 1,000,000 steps; binary search takes at most 20 steps (2²⁰ ≈ 1.05 × 10⁶).
  • n = 1,000,000,000 (10⁹): linear search takes 10⁹ steps; binary search takes at most 30 steps (2³⁰ ≈ 1.07 × 10⁹).
  • n = 4 × 10¹⁸ (Long.MAX_VALUE is ≈ 9.22 × 10¹⁸): binary search takes at most 63 steps!

How to spot this pattern

Reach for binary search when one check can throw away half of the options. Look for these clues in the problem.

  • The data is sorted, or a yes/no test flips only once (false, false, true, true): use binary search.
  • The question asks for a position, a first or last occurrence, a boundary or "the smallest value that works": use lower or upper bound, or binary search on the answer.
  • The input is large (about 10⁵ or more) and the brute force is O(n) or O(n²): aim for O(log n).
  • Phrases such as "in O(log n)", "minimum capacity" or "smallest x such that" point to this technique.

Next step

Check your understanding

10 quick questions