function ternarySearch(array: number[], target: number) {let low = 0, high = array.length - 1;
while (low <= high) {const third = Math.floor((high - low) / 3);
const first = low + third, second = high - third;
if (array[first] === target) return first;
if (array[second] === target) return second;
if (target < array[first]) high = first - 1;
else if (target > array[second]) low = second + 1;
else { low = first + 1; high = second - 1; }}
return -1;
}
Look for 33. Two probes per round split the range into three thirds.
Understanding Ternary search
The idea
Ternary search cuts the range at two points, a third and two thirds of the way in, and compares the target with both. That tells which of the three thirds holds the target, so the range shrinks by a factor of three per round instead of two: log₃ n rounds instead of log₂ n.
Each round costs two comparisons, though, and 2 log₃ n is larger than log₂ n. On a sorted array ternary search does more work than binary search. Its real use is different: finding the maximum of a unimodal function, where two probes are needed to know which side is climbing.
The four stages
Complexity
Versus its siblings
Pseudocode
TERNARYSEARCH(array, target)
low ← 0; high ← n − 1
while low ≤ high
first ← low + ⌊(high − low) / 3⌋; second ← high − ⌊(high − low) / 3⌋
if array[first] = target or array[second] = target: return it
if target < array[first]: high ← first − 1; else if target > array[second]: low ← second + 1; else: low ← first + 1, high ← second − 1
return −1
When to use
Pitfalls
History
Ternary search on functions is a classic of numerical optimisation, a cousin of golden-section search, which reuses one of the two probes per round and needs only 1.44 log n evaluations. As an array search it survives mostly as an interview question about why it is not better than binary search.