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 .