Ternary search keeps the mode in its interval and shrinks the interval by a factor of at least 2/3 full
This proof shows: correctness.
We use the pseudocode of the page. Let f be strictly unimodal for a maximum on its domain, with mode m, as defined on the page unimodal function. We use its comparison lemma: for x1<x2, f(x1)<f(x2) implies m>x1; f(x1)>f(x2) implies m<x2; and f(x1)=f(x2) implies x1<m<x2.
Claim 1 (real version). If m∈[lo,hi] before the call of TERNARY-MAX(f,lo,hi,steps), then after the loop m∈[lo,hi] and hi−lo=(2/3)steps times the initial length. The returned point is within half of that length of m.
Proof. Invariant: before each iteration, m∈[lo,hi]. It holds at the start by assumption. In an iteration, lines L2 and L3 give lo<m1<m2<hi when lo<hi, with m1−lo=hi−m2=(hi−lo)/3.
- If f(m1)<f(m2) (line L4), then m>m1, so m∈(m1,hi]⊆[m1,hi], the new interval.
- Else f(m1)≥f(m2). If the inequality is strict, m<m2. If the values are equal, m1<m<m2. In both cases m∈[lo,m2), the new interval of line L5.
So the invariant holds after the iteration. In both branches the new length is (hi−lo)−(hi−lo)/3=32(hi−lo). After steps iterations the length is (2/3)steps times the initial one. Line L6 returns the midpoint of an interval that holds m, so its distance to m is at most half the length. If lo=hi at some point, then m=lo and every later iteration keeps lo=hi. □
The proof uses exact arithmetic. In floating point the computed m1 and m2 can be equal when the interval holds few doubles; the case analysis then still keeps m in the interval, but the length stops shrinking.
Claim 2 (integer version). For integers lo≤hi with m∈{lo,…,hi}, TERNARY-INT(f,lo,hi) returns m. With n=hi−lo+1≥2 candidates it makes at most ⌈log3/2n⌉ iterations and 2⌈log3/2n⌉ evaluations of f.
Proof. Invariant: lo≤m≤hi before each test of line L7. It holds at the start. In an iteration lo<hi; let ℓ=hi−lo≥1 and d=⌊ℓ/3⌋≥0 (line L8). Line L9 sets m1=lo+d and m2=hi−d, so m2−m1=ℓ−2d≥ℓ/3>0 and lo≤m1<m2≤hi.
- If f(m1)<f(m2), then m>m1, so m≥m1+1, the new lo of line L10. The bound m≤hi is unchanged.
- Else, as in Claim 1, m<m2, so m≤m2−1, the new hi of line L11.
So the invariant holds. When the loop stops, lo≥hi; together with lo≤m≤hi this gives lo=m=hi, and line L12 returns m.
Termination and count. Let s=hi−lo+1 be the number of candidates. One iteration removes at least d+1 of them, so the new count is at most s−1−⌊(s−1)/3⌋=⌈2(s−1)/3⌉≤32(s−1)+2=32s. The count drops by at least 1 per iteration, so the loop ends. After t iterations s≤(2/3)tn. The loop runs only while s≥2, so if it makes t≥1 iterations then 2≤(2/3)t−1n, that is t≤1+log3/2(n/2)<log3/2n, because log3/22>1. Hence t≤⌈log3/2n⌉. Each iteration evaluates f twice and nothing else does, which gives the bound on evaluations. □