DSAverse
Initializing Sorting Algorithms...
Sorting Algorithm
Binary Tree
Graph Traversal
Preparing interactive visualizations for optimal learning experience...
Initializing Sorting Algorithms...
Preparing interactive visualizations for optimal learning experience...
Initializing Sorting Algorithms...
Preparing interactive visualizations for optimal learning experience...
Watch how Ternary Search divides the array into three parts, eliminating 2/3 of the search space at each step.
Click Start to begin Ternary Search visualization
Despite eliminating more space, ternary search typically performs more total comparisons than binary search.
def ternary_search(arr, target, left=0, right=None):
if right is None:
right = len(arr) - 1
if left > right:
return -1
# Divide array into three parts
mid1 = left + (right - left) // 3
mid2 = right - (right - left) // 3
# Check if target is at mid1 or mid2
if arr[mid1] == target:
return mid1
if arr[mid2] == target:
return mid2
# Search in appropriate third
if target < arr[mid1]:
return ternary_search(arr, target, left, mid1 - 1)
elif target > arr[mid2]:
return ternary_search(arr, target, mid2 + 1, right)
else:
return ternary_search(arr, target, mid1 + 1, mid2 - 1)