Python Program to Implement Ternary Search

Python Program to Implement Ternary Search

Searching efficiently is an important skill in programming, and Ternary Search is a powerful algorithm designed for sorted datasets. Unlike binary search, which splits the array into two halves, Ternary Search divides it into three parts. This allows the search to narrow down more quickly in certain scenarios, making it a valuable tool for beginners to understand both recursion and divide-and-conquer strategies.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Ternary Search is often used in applications where large sorted datasets are common, such as databases, sorted lists, and optimization problems. By learning Ternary Search in Python, beginners can strengthen their algorithmic thinking, learn how to write recursive and iterative functions, and apply efficient searching methods in real-world programming tasks. In this article, we’ll explore multiple ways to implement Ternary Search in Python, including recursive, iterative, reusable, and safe approaches, making it easy to follow along and practice.

Program 1: Recursive Ternary Search

This program demonstrates the classic recursive approach to Ternary Search, dividing the array into three segments and recursively searching the correct segment for the target element.

def ternary_search(arr, left, right, target):

    if right >= left:

        mid1 = left + (right - left) // 3
        mid2 = right - (right - left) // 3

        if arr[mid1] == target:
            return mid1
        if arr[mid2] == target:
            return mid2

        if target < arr[mid1]:
            return ternary_search(arr, left, mid1 - 1, target)
        elif target > arr[mid2]:
            return ternary_search(arr, mid2 + 1, right, target)
        else:
            return ternary_search(arr, mid1 + 1, mid2 - 1, target)

    return -1


arr = [10, 20, 30, 40, 50, 60, 70]
target = 50
result = ternary_search(arr, 0, len(arr) - 1, target)

if result != -1:
    print(f"Element {target} found at index {result}")
else:
    print(f"Element {target} not found in the list")

In this recursive approach, the array is split using two midpoints. Each recursive call narrows down the search space until the target is found or confirmed absent. Beginners can easily understand how recursion breaks a problem into smaller, manageable pieces.

Program 2: Iterative Ternary Search

This example uses an iterative approach to implement Ternary Search, avoiding recursion while achieving the same results.

def ternary_search_iterative(arr, target):

    left, right = 0, len(arr) - 1

    while left <= right:

        mid1 = left + (right - left) // 3
        mid2 = right - (right - left) // 3

        if arr[mid1] == target:
            return mid1
        if arr[mid2] == target:
            return mid2

        if target < arr[mid1]:
            right = mid1 - 1
        elif target > arr[mid2]:
            left = mid2 + 1
        else:
            left = mid1 + 1
            right = mid2 - 1

    return -1

arr = [5, 15, 25, 35, 45, 55]
target = 35
result = ternary_search_iterative(arr, target)

if result != -1:
    print(f"Element {target} found at index {result}")
else:
    print(f"Element {target} not found in the list")

The iterative method shows how loops can replace recursion while maintaining the divide-and-conquer logic. Beginners can follow how the search space is gradually reduced until the target is found.

Program 3: Ternary Search on a Large Dataset

This program applies Ternary Search to a larger array to illustrate its efficiency in reducing the number of comparisons.

def ternary_search_large(arr, target):

    left, right = 0, len(arr) - 1

    while left <= right:

        mid1 = left + (right - left) // 3
        mid2 = right - (right - left) // 3

        if arr[mid1] == target:
            return mid1
        if arr[mid2] == target:
            return mid2

        if target < arr[mid1]:
            right = mid1 - 1
        elif target > arr[mid2]:
            left = mid2 + 1
        else:
            left = mid1 + 1
            right = mid2 - 1

    return -1


arr = [i*2 for i in range(100)]
target = 88
result = ternary_search_large(arr, target)

if result != -1:
    print(f"Element {target} found at index {result}")
else:
    print(f"Element {target} not found in the list")

By using Ternary Search on 100 elements, beginners can observe how splitting the array into three parts significantly reduces comparisons compared to linear search. This demonstrates the efficiency of divide-and-conquer algorithms.

Program 4: Reusable Recursive Function

This example wraps the Ternary Search logic in a reusable function, allowing easy repeated searches on different elements or arrays.

def reusable_ternary_search(arr, left, right, target):

    if right >= left:

        mid1 = left + (right - left) // 3
        mid2 = right - (right - left) // 3

        if arr[mid1] == target:
            return mid1
        if arr[mid2] == target:
            return mid2

        if target < arr[mid1]:
            return reusable_ternary_search(arr, left, mid1 - 1, target)
        elif target > arr[mid2]:
            return reusable_ternary_search(arr, mid2 + 1, right, target)
        else:
            return reusable_ternary_search(arr, mid1 + 1, mid2 - 1, target)

    return -1


arr = [3, 6, 9, 12, 15, 18, 21]
target = 15
result = reusable_ternary_search(arr, 0, len(arr)-1, target)

if result != -1:
    print(f"Element {target} found at index {result}")
else:
    print(f"Element {target} not found in the list")

Using a reusable function shows beginners how to write modular code, making the Ternary Search logic easy to apply to different problems without rewriting it.

Program 5: Ternary Search with Error Handling

This program demonstrates a safe implementation that handles empty lists and cases where the target element is not present.

def safe_ternary_search(arr, left, right, target):

    if not arr:
        return -1

    if right >= left:

        mid1 = left + (right - left) // 3
        mid2 = right - (right - left) // 3

        if arr[mid1] == target:
            return mid1
        if arr[mid2] == target:
            return mid2

        if target < arr[mid1]:
            return safe_ternary_search(arr, left, mid1 - 1, target)
        elif target > arr[mid2]:
            return safe_ternary_search(arr, mid2 + 1, right, target)
        else:
            return safe_ternary_search(arr, mid1 + 1, mid2 - 1, target)

    return -1


arr = [7, 14, 21, 28, 35, 42]
target = 21
result = safe_ternary_search(arr, 0, len(arr)-1, target)

if result != -1:
    print(f"Element {target} found at index {result}")
else:
    print(f"Element {target} not found in the list")

Error handling ensures the program works safely with empty arrays or when the target is missing. Beginners learn the importance of writing robust code alongside implementing efficient algorithms.

Program 6: Ternary Search on a Function (Finding Minimum or Maximum)

Ternary Search can also be used beyond arrays—it can help find the minimum or maximum value of a function that is unimodal (that is, it increases and then decreases, or vice versa). Let’s look at a simple example that uses Ternary Search to find the minimum point of a mathematical function.

def f(x):
    return (x - 2) ** 2 + 3  # Minimum occurs near x = 2


def ternary_search_function(left, right, epsilon=1e-5):

    while right - left > epsilon:

        mid1 = left + (right - left) / 3
        mid2 = right - (right - left) / 3

        if f(mid1) < f(mid2):
            right = mid2
        else:
            left = mid1

    return (left + right) / 2


result = ternary_search_function(-10, 10)

print(f"The minimum point of the function is near x = {result:.5f}")

In this version, instead of searching for a value inside a list, we’re finding the minimum value of a continuous function. The algorithm repeatedly narrows down the range by comparing values of the function at two midpoints. Beginners can use this as an introduction to optimization problems, showing how the same algorithmic thinking applies in different contexts.

Frequently Asked Questions (FAQ)

Ternary Search is a practical algorithm for sorted datasets, and beginners often have questions about its usage and efficiency.

Q1: What is Ternary Search used for?
Ternary Search is used to locate elements in sorted arrays efficiently by dividing the search space into three parts.

Q2: Can it work on unsorted arrays?
No, the array must be sorted for Ternary Search to function correctly.

Q3: Is Ternary Search faster than binary search?
While it can reduce comparisons slightly, binary search is often simpler and faster in practice for most datasets.

Q4: How are the midpoints calculated?
Two midpoints divide the array into three equal segments, helping the search narrow down efficiently.

Q5: Why should beginners learn Ternary Search?
It teaches recursion, iterative logic, divide-and-conquer strategies, and efficient searching in a structured way, building a strong foundation for more complex algorithms.

Conclusion

Ternary Search is a valuable algorithm for efficiently searching sorted arrays in Python. By exploring recursive, iterative, reusable, and safe implementations, beginners can understand core programming concepts such as recursion, loops, modular code, and error handling.

Practicing these examples helps learners strengthen problem-solving skills and gain confidence in algorithmic thinking. By experimenting with different approaches and handling edge cases, beginners can develop a solid understanding of efficient searching methods that can be applied to larger datasets and real-world programming challenges.

Scroll to Top