Uploaded by Yoga PP

18222073 Ternary Search Algorithm

advertisement
Name : Yoga Putra Pratama
ID
: 18222073
TERNARY SEARCH ALGORITHM
Question
1. Write the pseudocode of a ternary search algorithm and find a big-O estimate for the
worst-case complexity in terms of number of comparisons used.
2. How does it perform compared to the binary search algorithm?
Answer
1.
function ternary_search(arr, target)
left = 0
right = length(arr) - 1
while left <= right
# Calculate two midpoints
mid1 = left + (right - left) // 3
mid2 = right - (right - left) // 3
if arr[mid1] == target then
return mid1
if arr[mid2] == target then
return mid2
if target < arr[mid1] then
right = mid1 - 1
elif target > arr[mid2] then
left = mid2 + 1
else
left = mid1 + 1
right = mid2 - 1
return -1 # Target not found in the array
The worst-case complexity of the ternary search algorithm in terms of the number of
comparisons used can be estimated as O(log3(n)), where 'n' is the size of the input array.
2. Comparison between binary search and ternary search :
Worst-Case
Division of Search
Complexity
Space
Binary Search
O(log2(n))
Divides the search
space into two equal
parts
Ternary Search
O(log3(n))
Divides the search
space into three
parts
Use Cases
Often preferred when you
need to find an exact match
in a sorted array
Can be useful in cases
where you suspect that the
target element is more
likely to be located in one
of the three segments after
the initial division
Download