Ternary search
28 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Binary search finds where a monotonic function crosses a target. What if a function is unimodal—it rises to a single peak and then falls, or falls to a single valley and then rises (like travel time as a function of speed, or total cost of leveling array elements to height x)? Evaluating just one midpoint mid cannot tell you whether the peak is to the left or right of mid—so ternary search evaluates two interior points m1 and m2!
Unimodal functions: one peak or one valley
Ternary search finds the peak of a function that rises and then falls by comparing two points and discarding the third of the range that cannot hold the peak.
A function f(x) on an interval [lo, hi] is unimodal if it has a single extremum: one peak (rises, then falls) or one valley (falls, then rises).
public class OneValley { static int f(int x) { return (x - 3) * (x - 3); // decreases until x = 3, then increases }
public static void main(String[] args) { for (int x = 0; x <= 6; x++) { System.out.println("f(" + x + ") = " + f(x)); } }}f(0) = 9 f(1) = 4 f(2) = 1 f(3) = 0 f(4) = 1 f(5) = 4 f(6) = 9
Why isn't one point enough? If you evaluate only f(mid), the curve could still be rising toward the extremum or already falling from it. Two interior points m₁ < m₂ reveal the slope between them.
- Finding a valley (minimum): if f(m₁) < f(m₂), the minimum cannot lie in (m₂, hi], so set
hi = m2; otherwise the minimum cannot lie in [lo, m₁), so setlo = m1. - Finding a peak (maximum): if f(m₁) < f(m₂), the peak cannot lie in [lo, m₁), so set
lo = m1; otherwise sethi = m2.
Splitting the range in three
Given range [lo, hi], ternary search places two trisection points at the one-third and two-thirds marks:
- m₁ = lo + (hi - lo) / 3
- m₂ = hi - (hi - lo) / 3
static int valleyX(int lo, int hi) { while (hi - lo > 2) { int m1 = lo + (hi - lo) / 3; // one-third mark int m2 = hi - (hi - lo) / 3; // two-thirds mark if (f(m1) < f(m2)) hi = m2; // the valley is not right of m2 else lo = m1; // the valley is not left of m1 } int best = lo; // at most 3 values left: check each one for (int x = lo + 1; x <= hi; x++) { if (f(x) < f(best)) best = x; } return best;}These two points divide [lo, hi] into three equal thirds: [lo, m₁], [m₁, m₂], and [m₂, hi]. Every comparison discards either the leftmost third or the rightmost third, shrinking the interval length to 2/3 of its previous size!
After k iterations, the interval shrinks by (2/3)ᵏ. Because log₃/2(n) = (ln n)/(ln 1.5) ≈ 1.71 ln n, ternary search still runs in O(log n) time!
- Compute
m1 = lo + (hi - lo) / 3andm2 = hi - (hi - lo) / 3. - Evaluate
f(m1)andf(m2). - Discard the outer third that cannot contain the extremum (
lo = m1orhi = m2).
Ternary search on integers and on doubles
Ternary search behaves slightly differently on continuous double intervals vs discrete int intervals:
- On
doubleintervals: run a fixed number of iterations (typically80to100iterations).
Example 1 · Ternary search on doubles: finding the minimum of a convex function
public class TernarySearchDoubleDemo { // Convex parabola f(x) = (x - 3.5)^2 + 12.25, minimum at x = 3.5 with value 12.25 public static double f(double x) { return (x - 3.5) * (x - 3.5) + 12.25; }
public static double findMinX(double lo, double hi) { for (int iter = 0; iter < 100; iter++) { double m1 = lo + (hi - lo) / 3.0; double m2 = hi - (hi - lo) / 3.0; if (f(m1) < f(m2)) { hi = m2; // minimum is not in (m2, hi] } else { lo = m1; // minimum is not in [lo, m1) } } return (lo + hi) / 2.0; }
public static void main(String[] args) { double xStar = findMinX(-100.0, 100.0); System.out.printf("x* = %.4f, f(x*) = %.4f%n", xStar, f(xStar)); }}x* = 3.5000, f(x*) = 12.2500
What this code does
- 100 iterations shrink the interval width 200.0 by (2/3)^100, pinpointing x* = 3.5000 to full double precision.
- Using a fixed iteration count avoids any while (hi - lo > eps) infinite loop when eps is smaller than machine epsilon.
Example 2 · Ternary search on integers with the while (hi - lo >= 3) pattern
public class TernarySearchIntDemo { // Minimum Cost to Make Array Equal: convex cost function! public static long totalCost(int[] nums, int[] cost, int target) { long sum = 0; for (int i = 0; i < nums.length; i++) { sum += (long) Math.abs(nums[i] - target) * cost[i]; } return sum; }
public static long minCostTernary(int[] nums, int[] cost) { int lo = Integer.MAX_VALUE, hi = Integer.MIN_VALUE; for (int x : nums) { lo = Math.min(lo, x); hi = Math.max(hi, x); } while (hi - lo >= 3) { int m1 = lo + (hi - lo) / 3; int m2 = hi - (hi - lo) / 3; if (totalCost(nums, cost, m1) <= totalCost(nums, cost, m2)) { hi = m2; } else { lo = m1; } } long ans = Long.MAX_VALUE; for (int x = lo; x <= hi; x++) { ans = Math.min(ans, totalCost(nums, cost, x)); } return ans; }
public static void main(String[] args) { int[] nums = {1, 3, 5, 2}; int[] cost = {2, 3, 1, 14}; System.out.println("Min cost: " + minCostTernary(nums, cost)); }}Min cost: 8
What this code does
- Because totalCost(x) is a sum of V-shaped absolute value functions |nums[i] - x| * cost[i], it is convex (one valley).
- Once hi - lo < 3, the tiny final loop checks the remaining 2 or 3 integer candidates directly.
Since (2/3)¹⁰⁰ ≈ 2.45 × 10⁻¹⁸, 100 iterations narrow any reasonable interval down to full 64-bit double precision without risking floating-point infinite loops!
- On
intintervals: whenhi - lo < 3, integer division(hi - lo) / 3becomes0, which would makem1 == loandm2 == hiand cause an infinite loop! So loopwhile (hi - lo >= 3), updatelo = m1orhi = m2(orlo = m1 + 1/hi = m2 - 1whenm1 < m2), and oncehi - lo < 3(at most 3 integers left), checklo .. hiwith a tinyforloop!
while (hi - lo >= 3) on integer ternary search and finishing with a 3-element for loop from lo to hi is 100% immune to rounding and off-by-one bugs!When binary search on the slope is simpler
When you are searching a discrete integer range [lo .. hi], you do not even need ternary search.
Example 3 · Binary search on the slope (mid vs mid + 1) on the same integer problem
public class SlopeBinarySearchDemo { public static long totalCost(int[] nums, int[] cost, int target) { long sum = 0; for (int i = 0; i < nums.length; i++) { sum += (long) Math.abs(nums[i] - target) * cost[i]; } return sum; }
public static long minCostSlopeBS(int[] nums, int[] cost) { int lo = 1, hi = 5; while (lo < hi) { int mid = lo + (hi - lo) / 2; if (totalCost(nums, cost, mid) <= totalCost(nums, cost, mid + 1)) { hi = mid; // slope is non-negative (rising), valley is at or left of mid } else { lo = mid + 1; // slope is negative (falling), valley is right of mid } } return totalCost(nums, cost, lo); }
public static void main(String[] args) { int[] nums = {1, 3, 5, 2}; int[] cost = {2, 3, 1, 14}; System.out.println("Optimal target x = 2 gives cost: " + minCostSlopeBS(nums, cost)); }}Optimal target x = 2 gives cost: 8
What this code does
- Comparing totalCost(mid) <= totalCost(mid + 1) halves the integer range at every step instead of multiplying by 2/3.
- It requires no special while (hi - lo >= 3) post-loop and makes ~30% fewer function evaluations than integer ternary search!
Instead of placing m1 and m2 a third of the way apart, place them 1 unit apart at mid and mid + 1! Comparing f(mid) with f(mid + 1) tests the discrete derivative (slope) Δ f(mid) = f(mid + 1) - f(mid):
- For a valley (minimum): if
f(mid) <= f(mid + 1), the curve is already rising atmid, sohi = mid; elselo = mid + 1. - For a peak (maximum): if
f(mid) < f(mid + 1), the curve is still rising atmid, solo = mid + 1; elsehi = mid. On integers, binary search on the slope (midvsmid + 1) halves the range by 1/2 instead of 2/3 (fewer function evaluations!) and uses the exact same 6-line loop asfindPeakElement. Reserve true ternary search (1/3and2/3) for continuousdoublefunctions wheremid + 1is too wide andmid + epssuffers from floating-point cancellation!
Next step
Check your understanding
10 quick questions