guest@cp-base:~/home/binary-search$
templates/ternary-search.cpp
compilable
$cat templates/ternary-search

Ternary Search

Find the max or min of a unimodal function on a continuous interval in O(log(range/eps)).

#ternary-search#unimodal#optimization#continuous
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <bits/stdc++.h>
using namespace std;
using ld = long double;

ld ternaryMax(function<ld(ld)> f, ld l, ld r, int iter = 200) {
    for (int i = 0; i < iter; i++) {
        ld m1 = l + (r - l) / 3.0;
        ld m2 = r - (r - l) / 3.0;
        if (f(m1) < f(m2)) l = m1;
        else r = m2;
    }
    return (l + r) / 2.0;
}

ld ternaryMin(function<ld(ld)> f, ld l, ld r, int iter = 200) {
    for (int i = 0; i < iter; i++) {
        ld m1 = l + (r - l) / 3.0;
        ld m2 = r - (r - l) / 3.0;
        if (f(m1) > f(m2)) l = m1;
        else r = m2;
    }
    return (l + r) / 2.0;
}
23 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)

Ternary Search

Locates the maximum or minimum of a unimodal function over a continuous interval [l,r][l, r].

How It Works

  • Compute two interior points: m1=l+(rl)/3m_1 = l + (r-l)/3, m2=r(rl)/3m_2 = r - (r-l)/3

  • Compare f(m1)f(m_1) and f(m2)f(m_2)

  • Eliminate one-third of the interval based on comparison

  • After kk iterations, remaining interval has length (2/3)k(rl)(2/3)^k \cdot (r-l)
  • Finding Maximum

  • If f(m1)<f(m2)f(m_1) < f(m_2): maximum is in [m1,r][m_1, r], set l=m1l = m_1

  • Otherwise: maximum is in [l,m2][l, m_2], set r=m2r = m_2
  • Finding Minimum

  • Flip the comparison, or negate ff and use max version
  • When to Use

  • Unimodal functions (single peak or single valley)

  • Geometric optimization, distance minimization

  • When binary search needs a monotonic predicate but the function isn't monotonic
  • Complexity

  • 200 iterations gives precision 1035\approx 10^{-35}, far beyond double precision

  • Time — O(iterationsT(f))O(\text{iterations} \cdot T(f))