Ternary search
A sheet of cardboard can be folded into boxes of different sizes. The volume first increases as the cut size grows, then decreases. To find the largest volume, we need to locate the maximum of a function rather than search for a particular value.
Ternary search finds the maximum or minimum of a unimodal sequence or function by comparing two positions and discarding part of the search interval on each iteration.
Unimodal sequences
Consider the array 8 9 11 12 14 15 17 16 6 1, indexed from 0. Its values strictly increase up to the maximum, 17 at index 6, and then strictly decrease. Such a sequence is called unimodal. A linear scan finds the maximum in time.
Fig. 1. Ten numbers that rise to 17 at index 6, then fall.
Unlike a sorted array, a unimodal array does not let us decide where the maximum lies by looking at a single middle element. The two sequences below both contain 14 at index 4, but their maxima are on different sides.
Fig. 2. Both arrays hold 14 in the middle (red), but their tops (blue) are on different sides.
Comparing neighbouring elements tells us whether the array is increasing or decreasing at that position. For a discrete array, this leads to a useful binary search alternative. For functions of a real variable, there is no next index, so ternary search compares two separated positions instead.
How ternary search works
Maintain an inclusive interval [l,r] containing a maximum. Choose two positions:
If f(m_1)<f(m_2), the maximum cannot lie strictly to the left of m_1: if it did, both positions would be on the decreasing side and the first value would be larger. Therefore, set l = m1. If the first value is larger, set r = m2. For a strictly unimodal sequence, equal values mean the maximum lies between the two positions, so either update is safe.
Each iteration removes roughly one third of the remaining interval. For an integer range of positions, the algorithm needs O(\log n) iterations. When at most three integer positions remain, check them directly.
The top is somewhere from l = 0 to r = 9. The arrows mark l and r.
Fig. 3. Step through ternary search with the buttons or the arrow keys. Blue cells are the two looks, grey cells are dropped, and the top is green at the end.
For small arrays, a linear scan may perform fewer comparisons. For a million positions, ternary search needs only a few dozen iterations, provided the values can be evaluated without first scanning all of them.
Implementing integer ternary search
The search interval is inclusive. For integer positions, calculate the two interior positions using integer division.
while (r - l > 2) {
int m1 = l + (r - l) / 3;
int m2 = r - (r - l) / 3;
if (a[m1] < a[m2]) l = m1;
else r = m2;
}The program reads a non-empty unimodal array and prints an index of its maximum and the corresponding value.
Input:
10
8 9 11 12 14 15 17 16 6 1Output:
6 17#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
// start: the top is somewhere in 0..n-1
int l = 0, r = n - 1;
// the top always stays somewhere from l to r
while (r - l > 2) {
// look: one third and two thirds of the way
int m1 = l + (r - l) / 3;
int m2 = r - (r - l) / 3;
// compare and drop (for a function, replace a[m] with f(m))
if (a[m1] < a[m2]) l = m1; // the top is not left of m1
else r = m2; // the top is not right of m2
}
// finish: at most 3 places are left
int best = l;
for (int i = l + 1; i <= r; i++)
if (a[i] > a[best]) best = i;
cout << best << ' ' << a[best] << '\n';
}The search itself takes O(\log n) time and additional memory. Reading the entire input array still costs time. When evaluating a function costs , searching an integer interval of positions costs O(T\log K) for K\ge2.
Maximum and minimum
if (f(m1) < f(m2)) l = m1;
else r = m2;To find a minimum, the function must decrease before its minimum and increase afterwards. Change the comparison in the final scan as well.
Searching real-valued functions
Cut squares of side from the four corners of a square sheet of cardboard of side 12 cm, then fold up the sides. The resulting open box has height and base dimensions 12-2x by 12-2x. Its volume is f(x)=x(12-2x)^2 for 0\le x\le6. This function increases to its maximum and then decreases.
The same two looks work on the function: look at one third and two thirds of the way from 0 to 6, that is at 2 and 4. The volumes are 128 and 64, so everything after 4 is dropped. There are no places to list, so instead of stopping at three places the loop runs a fixed number of rounds, as binary search does on real numbers.
Fig. 4. Each round drops the third beyond the look with the smaller volume.
The largest box comes from x = 2, with volume 128.
Code for a function of a real number
The program reads the positive side length s and searches the interval from 0 to s / 2 using 100 iterations. For input 12, the approximate result is a cut size of 2 cm and a volume of 128 cubic centimetres.
#include <cstdio>
double s;
double volume(double x) {
return x * (s - 2 * x) * (s - 2 * x);
}
int main() {
scanf("%lf", &s);
// start: the cut is between 0 and s / 2
double l = 0, r = s / 2;
for (int it = 0; it < 100; it++) {
// look
double m1 = l + (r - l) / 3;
double m2 = r - (r - l) / 3;
// compare and drop
if (volume(m1) < volume(m2)) l = m1;
else r = m2;
}
// finish
printf("%.6f %.6f\n", l, volume(l));
}Correctness
Let be the index of the top. The loop keeps one invariant: the top is always somewhere from l to r. In symbols, l \le t \le r.
The comparison rule above shows that each strict comparison keeps between and . If a_{m_1} = a_{m_2}, the looks can't be both on the rising or both on the falling side, so m_1 < t < m_2 and either move is safe.
Each round drops at least one place (see Implementation), so the loop ends with at most three places from to . The top is one of them, and the finish checks them all.
When ternary search does not work
The proof used that the numbers only rise before the top and only fall after it. With two tops this fails. In 1, 9, 2, 3, 4, 5, 6, 2, 1 the first round drops the 9, and the search returns 6.
Fig. 5. With two tops, the first round drops the higher one (red).
Flat stretches break the proof too: two equal numbers no longer have to be on different sides. On 1, 3, 3, 3, 3, 3, 9, 2 the first looks, at indices 2 and 5, both hold 3, r moves to 5, and the search returns 3 instead of 9. On such an array there is no logarithmic method in general; scan it in .
A flat maximum or minimum is safe if the function is strictly monotonic outside that optimal plateau. For example, the convex function |1-k|+|5-k| has minimum value 4 for every from 1 through 5. A sum of non-negative weighted absolute distances, \sum_i c_i|h_i-k|, has the same convexity property. In contrast, flat stretches away from the optimum can make the comparison inconclusive.
Common mistakes
Similar algorithms
Binary search finds where a yes/no check turns. On an array, the check "is a[m] < a[m + 1]?" from the discussion of unimodal sequences finds the top with about half the looks. For a real-valued function, an analogous comparison requires choosing a step size, which introduces another numerical approximation.
Golden-section search places the looks so that one of them is reused in the next round. Each round keeps about 0.618 of the range for one new look; ternary search keeps two thirds for two looks, which is \sqrt{2/3} \approx 0.816 per look.
The name "ternary search" is sometimes used for splitting a sorted array into three parts to find a value. That is binary search with two looks per round, and it gains nothing.
Practice
Çox asan (≈850)
Çox asan (≈850) · Ternary search
Asan (≈1000)
Çox asan (≈850)
Orta (≈1350) · Dynamic programming
Çox asan (≈850) · Math
Çətin (≈1650)