Ternary Search
When values rise to one peak and then fall, reading two points splits the range into thirds and shows which outer third cannot hold the peak. Drop it and repeat.
What Ternary Search Solves
A unimodal function rises to a single peak and then falls, or falls to a single valley and then rises. Profit as a price increases, the distance between two moving objects over time, and the error of a model as one setting changes often look like this. Ternary search finds the peak without checking every point.
It is not a way to search for a value in sorted data; binary search does that better, as the comparison below shows. Ternary search is for optimisation: where is the highest point? It is also unrelated to the ternary search tree, a trie variant with the same name.
- Input: a function or array that strictly rises, then strictly falls
- Output: the position of the maximum (flip the comparison for a minimum)
- Works on real-valued functions as well as arrays
The Rule: Drop a Third
- Set lo and hi to the ends of the range.
- While hi − lo > 2, compute m1 and m2 at the thirds and read f at both.
- If f(m1) < f(m2), set lo = m1 + 1; otherwise set hi = m2 − 1.
- Scan the two or three cells left and return the largest.
Pick two points that split lo..hi into thirds: m1 = lo + (hi − lo) / 3 and m2 = hi − (hi − lo) / 3. If f(m1) < f(m2), the peak cannot be left of m1, because then both points would lie on the falling side and f(m1) would be the larger. So set lo = m1 + 1. If f(m1) > f(m2), the peak cannot be right of m2, so set hi = m2 − 1.
On the hill 2, 5, 9, 14, 20, 27, 31, 33, 32, 28, 22, 15, 9, 4, 1, 0, round 1 compares 27 at index 5 with 22 at index 10 and drops 10..15. Rounds 2 to 4 cut the range to 0..9, 6..9 and 6..7. Scanning the last two cells finds the peak, 33 at index 7, after 10 reads instead of 16.
- Equal readings on a strictly unimodal function mean the peak is between them
- Stop at three or fewer cells, where the thirds collapse
- For a minimum, swap the comparison
Cost, and Ternary Search vs Binary Search
Each round reads two values and keeps 2/3 of the range, so it takes about log₁.₅ n rounds and 2 log₁.₅ n ≈ 3.4 log₂ n reads: O(log n) time and O(1) space.
On an integer array there is a cheaper method. Compare f(mid) with f(mid + 1): if the values are still rising, the peak is to the right; otherwise it is at mid or to the left. That also reads two values per round, but halves the range, so it needs about 2 log₂ n reads. On the 16-value hill it finds index 7 in 8 reads against ternary search's 10. This is the method used in the Find Peak Element problem.
For a plain target in a sorted array, ternary search loses as well. On 3, 7, 12, … 80 it needs 5 comparisons to find 69, binary search 3: two comparisons to shrink the range to a third is worse than one to shrink it to a half.
| Task | Ternary search | Binary search |
|---|---|---|
| Peak of the 16-value hill | 10 | 8 (on the slope) |
| Find 69 in the sorted array | 5 | 3 |
- Ternary: about 3.4 log₂ n reads; binary on the slope: about 2 log₂ n
- On arrays, binary search on the slope is the better choice
- Ternary search earns its place on continuous functions
Terms, operations, and practical uses
Key terms
- UnimodalStrictly increasing up to one peak, then strictly decreasing.
- Third-pointsm1 and m2, which split the range into three equal parts.
- Golden ratio φ0.618…, the shrink factor that lets golden-section search reuse a probe.
Related
- Binary searchHalving, and the slope comparison that beats ternary search on arrays.
- Find Peak ElementA peak in an array by binary search on the slope.
- Exponential searchAnother variation on narrowing a sorted range.
- Koko Eating BananasBinary search on the answer over a monotone function.
Code in Python, C++ and Java
def ternary_peak(f):
lo, hi, reads = 0, len(f) - 1, 0
while hi - lo > 2:
third = (hi - lo) // 3
m1, m2 = lo + third, hi - third
reads += 2
if f[m1] < f[m2]:
lo = m1 + 1
else:
hi = m2 - 1
best = lo
for i in range(lo, hi + 1):
reads += 1
if f[i] > f[best]:
best = i
return best, reads
def slope_peak(f):
lo, hi, reads = 0, len(f) - 1, 0
while lo < hi:
mid = (lo + hi) // 2
reads += 2
if f[mid] < f[mid + 1]:
lo = mid + 1
else:
hi = mid
return lo, reads
def ternary_find(a, target):
lo, hi, checks = 0, len(a) - 1, 0
while lo <= hi:
third = (hi - lo) // 3
m1, m2 = lo + third, hi - third
checks += 1
if a[m1] == target:
return m1, checks
if target < a[m1]:
hi = m1 - 1
continue
checks += 1
if a[m2] == target:
return m2, checks
if target > a[m2]:
lo = m2 + 1
else:
lo, hi = m1 + 1, m2 - 1
return -1, checks
hill = [2, 5, 9, 14, 20, 27, 31, 33, 32, 28, 22, 15, 9, 4, 1, 0]
flat = [1] * 13 + [9, 1, 1]
nums = [3, 7, 12, 18, 21, 27, 33, 38, 42, 47, 53, 58, 64, 69, 74, 80]
i, reads = ternary_peak(hill)
print(f"hill: peak at index {i} (value {hill[i]}), ternary {reads} reads")
i, reads = slope_peak(hill)
print(f"hill: peak at index {i}, binary search on the slope {reads} reads")
i, reads = ternary_peak(flat)
print(f"flat hill: answer index {i} (value {flat[i]}), true peak 9 at index 13")
i, checks = ternary_find(nums, 69)
print(f"sorted, find 69: index {i}, {checks} comparisons")#include <iostream>
#include <utility>
#include <vector>
using namespace std;
pair<int, int> ternaryPeak(const vector<int>& f) {
int lo = 0, hi = f.size() - 1, reads = 0;
while (hi - lo > 2) {
int third = (hi - lo) / 3, m1 = lo + third, m2 = hi - third;
reads += 2;
if (f[m1] < f[m2]) lo = m1 + 1;
else hi = m2 - 1;
}
int best = lo;
for (int i = lo; i <= hi; i++) {
reads++;
if (f[i] > f[best]) best = i;
}
return {best, reads};
}
pair<int, int> slopePeak(const vector<int>& f) {
int lo = 0, hi = f.size() - 1, reads = 0;
while (lo < hi) {
int mid = (lo + hi) / 2;
reads += 2;
if (f[mid] < f[mid + 1]) lo = mid + 1;
else hi = mid;
}
return {lo, reads};
}
pair<int, int> ternaryFind(const vector<int>& a, int target) {
int lo = 0, hi = a.size() - 1, checks = 0;
while (lo <= hi) {
int third = (hi - lo) / 3, m1 = lo + third, m2 = hi - third;
checks++;
if (a[m1] == target) return {m1, checks};
if (target < a[m1]) { hi = m1 - 1; continue; }
checks++;
if (a[m2] == target) return {m2, checks};
if (target > a[m2]) lo = m2 + 1;
else { lo = m1 + 1; hi = m2 - 1; }
}
return {-1, checks};
}
int main() {
vector<int> hill = {2, 5, 9, 14, 20, 27, 31, 33, 32, 28, 22, 15, 9, 4, 1, 0};
vector<int> flat(13, 1);
flat.insert(flat.end(), {9, 1, 1});
vector<int> nums = {3, 7, 12, 18, 21, 27, 33, 38, 42, 47, 53, 58, 64, 69, 74, 80};
auto [i, reads] = ternaryPeak(hill);
cout << "hill: peak at index " << i << " (value " << hill[i] << "), ternary " << reads << " reads\n";
auto [j, slope] = slopePeak(hill);
cout << "hill: peak at index " << j << ", binary search on the slope " << slope << " reads\n";
int k = ternaryPeak(flat).first;
cout << "flat hill: answer index " << k << " (value " << flat[k] << "), true peak 9 at index 13\n";
auto [f, checks] = ternaryFind(nums, 69);
cout << "sorted, find 69: index " << f << ", " << checks << " comparisons\n";
}public class Main {
static int[] ternaryPeak(int[] f) {
int lo = 0, hi = f.length - 1, reads = 0;
while (hi - lo > 2) {
int third = (hi - lo) / 3, m1 = lo + third, m2 = hi - third;
reads += 2;
if (f[m1] < f[m2]) lo = m1 + 1;
else hi = m2 - 1;
}
int best = lo;
for (int i = lo; i <= hi; i++) {
reads++;
if (f[i] > f[best]) best = i;
}
return new int[]{best, reads};
}
static int[] slopePeak(int[] f) {
int lo = 0, hi = f.length - 1, reads = 0;
while (lo < hi) {
int mid = (lo + hi) / 2;
reads += 2;
if (f[mid] < f[mid + 1]) lo = mid + 1;
else hi = mid;
}
return new int[]{lo, reads};
}
static int[] ternaryFind(int[] a, int target) {
int lo = 0, hi = a.length - 1, checks = 0;
while (lo <= hi) {
int third = (hi - lo) / 3, m1 = lo + third, m2 = hi - third;
checks++;
if (a[m1] == target) return new int[]{m1, checks};
if (target < a[m1]) { hi = m1 - 1; continue; }
checks++;
if (a[m2] == target) return new int[]{m2, checks};
if (target > a[m2]) lo = m2 + 1;
else { lo = m1 + 1; hi = m2 - 1; }
}
return new int[]{-1, checks};
}
public static void main(String[] args) {
int[] hill = {2, 5, 9, 14, 20, 27, 31, 33, 32, 28, 22, 15, 9, 4, 1, 0};
int[] flat = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 1, 1};
int[] nums = {3, 7, 12, 18, 21, 27, 33, 38, 42, 47, 53, 58, 64, 69, 74, 80};
int[] r = ternaryPeak(hill);
System.out.println("hill: peak at index " + r[0] + " (value " + hill[r[0]] + "), ternary " + r[1] + " reads");
r = slopePeak(hill);
System.out.println("hill: peak at index " + r[0] + ", binary search on the slope " + r[1] + " reads");
int k = ternaryPeak(flat)[0];
System.out.println("flat hill: answer index " + k + " (value " + flat[k] + "), true peak 9 at index 13");
r = ternaryFind(nums, 69);
System.out.println("sorted, find 69: index " + r[0] + ", " + r[1] + " comparisons");
}
}Step through it
Running on hill [2, 5, 9, 14, 20, 27, 31, 33, 32, 28, 22, 15, 9, 4, 1, 0]
Real-Valued Functions and Golden-Section Search
On a continuous function there is no next element to compare with, so the slope trick needs a derivative that may not be available. Ternary search only needs to evaluate f. Run it for a fixed number of rounds, say 100, rather than until lo equals hi, since floating-point values may never meet exactly. After 40 rounds an interval of width 6 has shrunk to about 5 × 10⁻⁷.
Golden section search improves on it. It places the two points at 0.382 and 0.618 of the range instead of 1/3 and 2/3. After dropping one side, the surviving inner point is exactly where the next round needs a probe, so each round needs only one new evaluation, and the range shrinks by 0.618 per evaluation instead of 0.816 per evaluation for ternary search. It matters when evaluating f is expensive, such as running a simulation.
- Use a fixed round count with floating-point ranges
- Golden section: one new evaluation per round, ratio 0.618
- Both need the function to be unimodal on the interval
When It Fails
The proof that a third can be dropped assumes strict rise and strict fall. On a plateau it breaks: with 1 in thirteen cells followed by a 9, round 1 reads 1 at both third-points, cannot tell the sides apart, and drops the third that holds the 9. A function with two peaks fails the same way, because the dropped third can hold the higher one.
Integer division also needs care. With hi − lo < 3 the two probes can coincide and the loop stops shrinking, which is why the loop ends at three cells and scans them.
- Plateaus and multiple peaks give wrong answers, not slow ones
- Check unimodality before using it, or search each unimodal piece separately
- End the loop at three cells to avoid an infinite loop