← All searching algorithms
Ternary Search
CheckingRuled outFound
array
target = 122
4
6
9
12
15
18
20
0lo
1
2
3
4
5
6
7hi
pseudocode
ternarySearch(a, target, lo, hi)while lo <= himid1 = lo + (hi - lo) / 3mid2 = hi - (hi - lo) / 3if a[mid1] == target return mid1if a[mid2] == target return mid2if target < a[mid1] hi = mid1 - 1else if target > a[mid2] lo = mid2 + 1else lo = mid1 + 1; hi = mid2 - 1return -1
Frame 1 / 5
Searching range [0…7] using two midpoints
divide range into 3 equal parts
4
Pick a value that is in the array — or one that isn't, to watch the search fail.
3–16 integers between 1 and 20 — the array is sorted for you, because binary search needs ordered data.