![]() |
VOOZH | about |
Ternary search is a divide-and-conquer search algorithm used to find the position of a target value within a monotonically increasing or decreasing function or in a unimodal array (e.g., U-shaped or ∩-shaped).
Unlike binary search, which splits the array into two parts, ternary search divides the range into three equal parts by choosing two mid-points:
Given an array that first strictly decreases and then strictly increases, we want to find the index of the minimum element. This kind of array is known as a U-shaped or unimodal array.
Input: arr [] = [9, 7, 5, 2, 3, 6, 10]
Output: 3
Explanation: The minimum of the given array is 2, which is at index 3.
Binary search works well for monotonic arrays (strictly increasing or strictly decreasing), but here the array is split into two parts:
This is exactly where ternary search fits best. It repeatedly narrows the search space by checking two middle points (mid1, mid2) and discarding one-third of the range based on the values at those points.
Ternary Search Logic (for this problem):
Let mid1 and mid2 be two points dividing the current interval into three equal parts:
We continue this until we reduce the search space to a small enough size to directly find the minimum.
Step by Step Implementation:
2
Time Complexity: O(2 × log3n)
Auxiliary Space: 1
Time Complexity:
Auxiliary Space: O(1)
Refer to here for more details
The time complexity of ternary search is slightly worse than binary search, primarily because ternary search performs more comparisons per iteration.
Binary search is ideal for finding values or extrema in monotonic functions (strictly increasing or decreasing), as it splits the search space into two parts.
On the other hand, ternary search is better suited for finding the maximum or minimum in unimodal functions, where the function first increases and then decreases (or vice versa).
Note: Ternary search can also be applied to monotonic functions, but it is generally less efficient than binary search due to its higher number of comparisons.
Refer to here for more details
Note: The array or function domain must follow a specific structure (e.g., sorted, monotonic, or unimodal) for ternary search to work correctly.