Ternary Search

Intermediate
Search
Requires sorted array

Ternary Search divides the search space into three parts per step using two mid-points (M1 and M2), eliminating one third each iteration. Theoretically requires more comparisons than Binary Search due to the higher base of the logarithm.

Auto-sorted: Array is automatically sorted. Each step computes two mid-points (M1 = L + ⌊(H-L)/3⌋, M2 = H - ⌊(H-L)/3⌋) and eliminates one third.

Search Target

Quick examples:

↑ Set a target value above to begin searching the array

Loading controls...
Loading visualization...
Time: O(log₃ n)
Space: O(1)

Legend

M1 — First mid-point
One-third mark: L + ⌊(H-L)/3⌋
M2 — Second mid-point
Two-thirds mark: H - ⌊(H-L)/3⌋
Found!
Target value located here
Active search window
Current [Low … High] range
Eliminated
Faded — third discarded this step
Not Found
Search space exhausted
Pointer labels on bars:
LLow boundary
M1First third mark
M2Second third mark
HHigh boundary
Found position

Inspector

No active frame to inspect

Reference implementation of Ternary Search. Select a language tab to view and copy the code.

def ternary_search(arr: list[int], target: int) -> int:
    left, right = 0, len(arr) - 1
    while left <= right:
        third = (right - left) // 3
        mid1  = left  + third
        mid2  = right - third

        if arr[mid1] == target: return mid1
        if arr[mid2] == target: return mid2

        if   target < arr[mid1]: right = mid1 - 1
        elif target > arr[mid2]: left  = mid2 + 1
        else:
            left, right = mid1 + 1, mid2 - 1
    return -1

Python — Code Walkthrough

  1. Floor division for third

    third = (right - left) // 3

    Python's // operator performs floor division, keeping third an integer. For a window of 10 elements: third = 3, mid1 = left+3, mid2 = right−3, giving three segments of sizes 3, 3, 4.

  2. Compact single-line returns

    if arr[mid1] == target: return mid1

    Python allows the if body on the same line as the colon when it's a single statement. This style is acceptable for short early returns but should not be overused.

  3. elif chain — four segments

    if ... elif ... else: left, right = mid1+1, mid2-1

    Python elif avoids deeply nested ifs. The final else clause narrows both bounds simultaneously using tuple assignment — idiomatic Python.

  4. Tuple swap for middle segment

    left, right = mid1 + 1, mid2 - 1

    Multiple assignment updates both bounds in a single statement. The right-hand side is fully evaluated before any assignment occurs, so no temp variable is needed.