Ternary Search, explained step by step

Ternary Search divides the sorted range into three parts using two probes and discards two thirds each round. It is mostly used to find the maximum or minimum of unimodal functions.

Intuition: Cut the problem into thirds and keep only the slice that can contain the answer.

How it works

  1. Compute mid1 and mid2 that split the range into thirds.
  2. Check both probes for the target.
  3. Keep the third that can contain the target and repeat.

Complexity

  • Best: O(1)
  • Average: O(log₃ n)
  • Worst: O(log₃ n)
  • Space: O(1)
  • Stable: no

When to use it

Finding the peak/valley of a unimodal function; for plain sorted lookups binary search is usually better.

Interview questions

  • Why does ternary search make more comparisons than binary search overall?
  • How is ternary search used on unimodal functions?

Compare Ternary Search

Open Ternary Search in the visualiser