Ternary Search visualization

Split a sorted range into thirds with two probes and keep the third that can hold the target.

Two midpoints m1 and m2 divide the range into three parts. Comparisons with both rule out two-thirds at a time. Fewer iterations than binary search, but more comparisons per iteration — it is most useful for finding the peak of unimodal functions.

Complexity

Time: best O(1), average O(log₃ n), worst O(log₃ n). Space: O(1). Difficulty: Intermediate.

Pseudocode

procedure ternarySearch(A, target):
  lo ← 0; hi ← n − 1
  while lo ≤ hi:
    m1 ← lo + (hi−lo)/3; m2 ← hi − (hi−lo)/3
    if A[m1] = target: return m1
    if A[m2] = target: return m2
    if target < A[m1]: hi ← m1 − 1
    else if target > A[m2]: lo ← m2 + 1
    else: lo ← m1 + 1; hi ← m2 − 1
  return −1

More searching algorithms