← Lessons

quiz vs the machine

Silver1120

Algorithms

Ternary Search on Real Functions

Find the peak of a unimodal function by shrinking the interval from both ends.

4 min read · intro · beat Silver to climb

When the function has one hump

Ternary search finds the maximum or minimum of a unimodal function on an interval. Unimodal means the function rises to a single peak and then falls, or falls to a single valley and then rises. Binary search needs monotonicity, but ternary search only needs this single turning point.

Cutting into thirds

Each step picks two interior probe points that split the current interval into three parts:

  • Evaluate the function at both probe points.
  • If the left probe gives a worse value, the peak cannot lie left of it, so discard the leftmost third.
  • Otherwise discard the rightmost third.

Either way the interval shrinks by a constant fraction, so after enough rounds the remaining window is tiny and any point inside is a good answer.

Practical notes

Because we work with real numbers we stop when the interval is smaller than a chosen tolerance, or after a fixed number of iterations. Floating point noise near a flat peak can mislead a strict comparison, so a fixed iteration count is often safer than waiting for exact equality.

Key idea

On a unimodal function, comparing two interior probes lets you discard a third of the interval each round until the peak is pinned down.

Check yourself

Answer to earn rating on the learn ladder.

1. What property must the function have for ternary search to work?

2. Why is a fixed iteration count often preferred over exact comparison?

3. How much of the interval is removed per step?