Loading...
Ternary search divides the search interval into three parts using two midpoints. It is mostly used to find the extremum (minimum/maximum) of a unimodal function. For searching a specific value in a sorted array, binary search is generally preferred.
Base change doesn't affect Big-O
Iterative approach
Versus 1 for binary search
def ternary_search(arr, target):
l, r = 0, len(arr) - 1
comparisons = 0
while l <= r:
third = (r - l) // 3
m1 = l + third
m2 = r - third
comparisons += 2
if arr[m1] == target:
return m1
if arr[m2] == target:
return m2
if target < arr[m1]:
r = m1 - 1
elif target > arr[m2]:
l = m2 + 1
else:
l = m1 + 1
r = m2 - 1
return -1
arr = [1, 2, 4, 4, 7, 9, 12, 15, 17, 18, 21, 24, 27, 30, 32, 35, 40, 42, 45, 50]
print(ternary_search(arr, 24))
Note: For locating a specific value in sorted arrays, binary search typically performs fewer comparisons overall.