Logarithm lecture

Why log n? A quick logarithm lecture

Binary search is O(log n). It's worth understanding why, because "logarithmic" is one of the best things an algorithm can be.

Halving

Each comparison in binary search throws away half the remaining candidates. Start with n, then n/2, then n/4, … How many halvings until you reach 1?

n → n/2 → n/4 → … → 1

That count is log₂(n) — the number of times you can halve n before hitting 1. Equivalently, 2^(steps) = n, so steps = log₂(n).

The numbers are staggering

n log₂(n) ≈ steps
1,000 10
1,000,000 20
1,000,000,000 30

A billion items, found in about 30 comparisons. Doubling the data adds just one step. That's the magic of logarithmic growth — it barely moves as n explodes.

Where logs show up

  • Binary search halves a range → O(log n).
  • Balanced trees / heaps have height ~log n → O(log n) operations.
  • Divide and conquer that splits in half and recurses gives the log factor in O(n log n) sorts.

Whenever you can halve the problem each step, you get a logarithm — and logarithms are so flat that O(log n) is, for practical purposes, almost free. Keep an eye out for "sorted" or "monotonic": it's usually an invitation to turn O(n) into O(log n).