AlgoFrames

Binary search

Find a value in a sorted array by looking at the middle and throwing away the half that cannot contain it, until one look remains.

Before you start: Linear search.

The idea

You never read a phone book from page one. You open it near the middle and jump.

Names are sorted, so one look tells you which half still matters. Binary search makes this habit precise.

Intuition

We want 9. The values are sorted, so look at the middle value first.

7 is smaller than 9. Everything left of 7 is smaller too, so drop that whole half.

Each look halves what is left. 8 values take 3 looks, not 8.

Halving 8 gives 4, then 2, then 1. The number of halvings to reach 1 is log2 n, which is 3 for n = 8.

Complexity

Linear search looks at up to n values. Binary search looks at about log2 n.

For a million values that is 20 looks instead of a million. The chart uses a linear scale, so the binary curve looks almost flat.

It uses only lo, hi and mid. Space is O(1) no matter how large the array.

Pitfalls

The array must be sorted. On unsorted values the halving rule throws away the wrong half.

Variations

With duplicates, keep searching left after a match to find the first occurrence.

Lower bound: the first value that is not smaller than the target, even when the target is missing.

Code

Pseudocode

lo ← 0, hi ← n - 1
while lo ≤ hi
  mid ← (lo + hi) / 2
  if a[mid] = target: return mid
  if a[mid] < target: lo ← mid + 1
  else: hi ← mid - 1
return -1

Python

def binary_search(a, target):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == target:
            return mid
        if a[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

JavaScript

function binarySearch(a, target) {
  let lo = 0, hi = a.length - 1;
  while (lo <= hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (a[mid] === target) return mid;
    if (a[mid] < target) lo = mid + 1;
    else hi = mid - 1;
  }
  return -1;
}

Java

static int binarySearch(int[] a, int target) {
    int lo = 0, hi = a.length - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] == target) return mid;
        if (a[mid] < target) lo = mid + 1;
        else hi = mid - 1;
    }
    return -1;
}

Cost at a glance

TimeO(log n)
SpaceO(1)
InputSorted array
OutputIndex of the target or -1

Practice problems (7)

Mid values Warm-up

Binary search looks for 38 in the sorted array [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]. Before each look, work out the index of mid.

Use mid = (lo + hi) / 2, rounded down.

Find the target Standard

Follow binary search for 11 in 16 sorted primes. Before each step plays, say which half survives and which cell comes next.

Implement binary search Standard

Given a sorted array of distinct integers nums and a target, return the index of target in nums, or -1 if it is not there.

The solution must run in O(log n) time.

Fix the off-by-one Standard

This binary search should return the index of target, or -1 when it is missing. It fails on some inputs where the target is present. Click the line with the bug, then fix it.

Square root floor Standard

Given a non-negative integer x, return the square root of x rounded down: the largest integer k with k × k ≤ x.

Do not use a built-in square root or power function. The solution must run in O(log x) time.

Search insert position Challenge

Given a sorted array of distinct integers nums and a target, return the index of target if it is present. Otherwise return the index where it would be inserted to keep the array sorted.

The solution must run in O(log n) time.

Which array can binary search use? Warm-up

Binary search needs one property of its input. Pick the array it can search correctly.

Next on the path: Bubble sort