AlgoLab

O(log n)·O(1) space
511181928314243454851515563647377969899

Search runs on a sorted copy of your array, because binary and jump search need sorted input. The bars are that sorted copy.

Searching a sorted array of 20 items for 51 by splitting the remaining range into thirds.

Searching a sorted array of 20 items for 51 by splitting the remaining range into thirds.
  1. 1set the low and high boundaries to the first and last position of the array
  2. 2split the range into three roughly equal parts using two markers, one third and two thirds of the way across
  3. 3compare the value at the first marker with the target
  4. 4the target is found
  5. 5compare the value at the second marker with the target
  6. 6the target is smaller than the first marker, so search the first third of the range
  7. 7the target is larger than the second marker, so search the last third of the range
  8. 8the target is between the two markers, so search the middle third of the range
  9. 9the target is not in the array
Comparisons
0
Writes
0
Accesses
0

Complexity

BestO(1)
AverageO(log n)
WorstO(log n)
Extra spaceO(1)
log₃ n at n=20 predicts 3; this run took 0.

Ternary search

Ternary search splits the remaining range into three roughly equal parts using two markers, compares the target against the value at each marker, and narrows to whichever third the target must be in — the first third, the last third, or the middle third between the two markers.

When it is the right choice

Ternary search is the right tool for one specific job it is not built for here: finding the peak or trough of a unimodal function, where each step needs two evaluations to know which slope you are on — a genuinely different problem from searching a sorted array. For searching a sorted array, which is what this tool shows, it is strictly worse than binary search: it makes two comparisons per step instead of one, while only cutting the range by a factor of three instead of two, and the coarser cut does not make up for the extra comparison. There is no honest case for choosing it over binary search here; it earns its page for showing that plainly.

How it works

Worth noticing

Cost

Best
O(1)
Average
O(log n)
Worst
O(log n)
Extra space
O(1)

Worth comparing

All algorithms