Algorithms · Visualized
Ternary Search
Searching Algorithms
Six search strategies on a sorted array — from the obvious linear scan to log-time binary search and beyond.
Ternary search finds a target in a sorted array — or the extremum of a unimodal function — by splitting the current range into three roughly equal parts using two midpoints, then discarding the one third that cannot contain the answer. Time: O(log₃ n) average, O(log₃ n), but 2 comparisons per step vs binary search's 1 worst; space: O(1) iterative, O(log n) recursive.
Big-O: Binary O(log n), Linear O(n), Jump O(√n), Interpolation O(log log n) avg, Exponential O(log n).
Ternary Search
SearchingTernary search finds a target in a sorted array — or the extremum of a unimodal function — by splitting the current range into three roughly equal parts using two midpoints, then discarding the one third that cannot contain the answer. It is divide-and-conquer like binary search but makes two comparisons per step, so it is usually slower on plain arrays; its real value is searching unimodal functions.
How Ternary Search Works
- Compute two midpoints m1 and m2 that split [low, high] into three equal parts.
- Compare the target against arr[m1] and arr[m2].
- If it matches either midpoint, return that index.
- If it is smaller than arr[m1], discard everything from m1 upward and search [low, m1-1].
- If it is larger than arr[m2], discard everything up to m2 and search [m2+1, high].
- Otherwise the target must be strictly between the midpoints — search [m1+1, m2-1].
Ternary Search Worked Example
Input: {array: [2, 5, 8, 12, 16, 23, 38, 56, 72, 91], target: 23}
low=0, high=9 → m1=3 (value 12), m2=6 (value 38). 23 > 12 and 23 < 38, so only the middle third [4,5] can hold it. low=4, high=5 → m1=4 (16), m2=5 (23) → match at m2. Found 23 at index 5.
def ternary_search(a, target):
lo, hi = 0, len(a) - 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
elif target > a[m2]:
lo = m2 + 1
else:
lo, hi = m1 + 1, m2 - 1
return -1Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Ternary Search Time & Space Complexity
When to Use Ternary Search
- Finding the peak of a unimodal (single-peak) function.
- Optimization over convex/concave value ranges.
- General sorted-array search, where binary search is usually preferred.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.