Implement Ternary Search in Python
Searching is one of the most fundamental operations in computer science, and there are multiple algorithms to perform it efficiently. While Binary Search is mainly known to be applied to sorted array searching, Ternary Search is another efficient searching technique that also works on sorted arrays for searching.
What is a Ternary Search
Ternary Search is a divide-and-conquer algorithm that splits the array into three parts instead of two (as in Binary Search). It repeatedly reduces the search space by two-thirds in each step, making it useful in cases where the dataset is large, and constant-time comparisons are expensive. In this article, we are going to discuss different approaches to implementing ternary search in Python.
Formula for Ternary Search
Given an array arr
, the two midpoints mid1
and mid2
are calculated as:
mid1 = low + (high ? low) / 3 mid2 = high - (high ? low) / 3
Example 1
Input: arr = [2, 5, 7, 12, 15, 18] key = 7 Output: Element found at index 2 Explanation: The array is divided into three parts. The key 7 matches the value at index 2.
Example 2
Input: arr = [10, 20, 30, 40, 50, 60] key = 25 Output: Element not found Explanation: The key 25 is not present in the array.
How to Implement Ternary Search in Python?
Below are different approaches to implementing Ternary Search in Python:
Implementing Ternary Search Using Iterative Approach
We use an iterative loop to implement Ternary Search. The array is repeatedly divided into three parts, and the search is narrowed down to the relevant section.
Steps for Implementation
- Take the input array and the key to search.
- Calculate the two midpoints
mid1
andmid2
. - Compare the key with the values at
mid1
andmid2
. - If found, return the index. Otherwise, update the bounds to narrow the search.
- Repeat until the bounds overlap or the element is found.
Implementation Code
# Iterative Ternary Search Function def ternary_search_iterative(arr, key): low, high = 0, len(arr) - 1 while low <= high: mid1 = low + (high - low) // 3 mid2 = high - (high - low) // 3 if arr[mid1] == key: return mid1 if arr[mid2] == key: return mid2 if key < arr[mid1]: high = mid1 - 1 elif key > arr[mid2]: low = mid2 + 1 else: low = mid1 + 1 high = mid2 - 1 return -1 # Example usage arr = [1, 3, 5, 7, 9, 11] key = 7 result = ternary_search_iterative(arr, key) if result != -1: print(f"Element found at index {result}") else: print("Element not found")
Output
Element found at index 3
Time Complexity: O(log3N)
Space Complexity: O(1)
Implementing Ternary Search Using Recursive Approach
In the recursive method, the function calls itself to narrow down the search region. This approach is compact and utilizes the call stack for repetitive operations.
Steps for Implementation
- Define a recursive function that takes the array, key, and bounds (low and high).
- Check if the bounds overlap. If they do, return -1.
- Calculate the two midpoints
mid1
andmid2
. - Compare the key with the values at
mid1
andmid2
. - If found, return the index. Otherwise, recursively call the function for the narrowed region.
Implementation Code
# Recursive Ternary Search Function def ternary_search_recursive(arr, key, low, high): if low > high: return -1 mid1 = low + (high - low) // 3 mid2 = high - (high - low) // 3 if arr[mid1] == key: return mid1 if arr[mid2] == key: return mid2 if key < arr[mid1]: return ternary_search_recursive(arr, key, low, mid1 - 1) elif key > arr[mid2]: return ternary_search_recursive(arr, key, mid2 + 1, high) else: return ternary_search_recursive(arr, key, mid1 + 1, mid2 - 1) # Example usage arr = [4, 8, 12, 16, 20, 24] key = 16 result = ternary_search_recursive(arr, key, 0, len(arr) - 1) if result != -1: print(f"Element found at index {result}") else: print("Element not found")
Output
Element found at index 3
Time Complexity: O(log3N)
Space Complexity: O(log3N)