Java Program to Implement Ternary Search

Java Program to Implement Ternary Search

Efficient searching is an essential skill for any programmer, and Ternary Search is a powerful algorithm that can help you locate elements faster in a sorted dataset. Unlike binary search, which divides the array into two parts, Ternary Search splits it into three segments. This approach allows you to narrow down the search more quickly in certain cases, making it an excellent technique to learn for beginners exploring algorithm optimization.

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 especially useful for searching in sorted arrays where performance matters, such as in large datasets, database records, or ordered lists. Understanding this algorithm not only helps in practical coding tasks but also introduces key programming concepts like recursion, divide-and-conquer strategies, and efficient array handling. In this article, we’ll explore multiple ways to implement Ternary Search in Java, including recursive, iterative, and error-handled approaches, providing easy-to-follow examples for beginners.

Program 1: Recursive Ternary Search

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

public class TernarySearchRecursive {

    static int ternarySearch(int[] arr, int left, int right, int target) {

        if (right >= left) {

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

            if (arr[mid1] == target) return mid1;
            if (arr[mid2] == target) return mid2;

            if (target < arr[mid1]) return ternarySearch(arr, left, mid1 - 1, target);
            else if (target > arr[mid2]) return ternarySearch(arr, mid2 + 1, right, target);
            else return ternarySearch(arr, mid1 + 1, mid2 - 1, target);

        }

        return -1;

    }

    public static void main(String[] args) {

        int[] arr = {10, 20, 30, 40, 50, 60, 70};
        int target = 50;
        int result = ternarySearch(arr, 0, arr.length - 1, target);

        if (result != -1)
            System.out.println("Element " + target + " found at index " + result);
        else
            System.out.println("Element " + target + " not found in the array");

    }

}

In this recursive approach, two midpoints split the array into three parts. By recursively checking the relevant segment, the algorithm efficiently narrows the search. Beginners can see how recursion simplifies problem-solving and reduces repetitive code.

Program 2: Iterative Ternary Search

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

public class TernarySearchIterative {

    static int ternarySearch(int[] arr, int target) {

        int left = 0, right = arr.length - 1;

        while (left <= right) {

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

            if (arr[mid1] == target) return mid1;
            if (arr[mid2] == target) return mid2;

            if (target < arr[mid1]) right = mid1 - 1;
            else if (target > arr[mid2]) left = mid2 + 1;
            else {
                left = mid1 + 1;
                right = mid2 - 1;
            }

        }

        return -1;

    }

    public static void main(String[] args) {

        int[] arr = {5, 15, 25, 35, 45, 55};
        int target = 35;
        int result = ternarySearch(arr, target);

        if (result != -1)
            System.out.println("Element " + target + " found at index " + result);
        else
            System.out.println("Element " + target + " not found in the array");

    }

}

The iterative method demonstrates how loops can replace recursion while performing the same divide-and-conquer logic. Beginners can visually follow how the search range shrinks step by step until the target is found or confirmed absent.

Program 3: Ternary Search on a Large Array

This program applies Ternary Search to a larger array, demonstrating its efficiency in reducing comparisons.

public class TernarySearchLarge {

    static int ternarySearch(int[] arr, int target) {

        int left = 0, right = arr.length - 1;

        while (left <= right) {

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

            if (arr[mid1] == target) return mid1;
            if (arr[mid2] == target) return mid2;

            if (target < arr[mid1]) right = mid1 - 1;

            else if (target > arr[mid2]) left = mid2 + 1;
            else {
                left = mid1 + 1;
                right = mid2 - 1;
            }

        }

        return -1;

    }

    public static void main(String[] args) {

        int[] arr = new int[100];

        for (int i = 0; i < 100; i++) arr[i] = i * 2;

        int target = 88;
        int result = ternarySearch(arr, target);

        if (result != -1)
            System.out.println("Element " + target + " found at index " + result);
        else
            System.out.println("Element " + target + " not found in the array");

    }

}

By using Ternary Search on 100 elements, beginners can appreciate the efficiency of dividing the search space into three parts. This reduces the number of comparisons compared to linear search, making the algorithm ideal for larger sorted datasets.

Program 4: Reusable Recursive Function

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

public class TernarySearchReusable {

    static int ternarySearch(int[] arr, int left, int right, int target) {

        if (right >= left) {

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

            if (arr[mid1] == target) return mid1;
            if (arr[mid2] == target) return mid2;

            if (target < arr[mid1]) return ternarySearch(arr, left, mid1 - 1, target);
            else if (target > arr[mid2]) return ternarySearch(arr, mid2 + 1, right, target);
            else return ternarySearch(arr, mid1 + 1, mid2 - 1, target);

        }

        return -1;

    }

    public static void main(String[] args) {

        int[] arr = {3, 6, 9, 12, 15, 18, 21};
        int target = 15;
        int result = ternarySearch(arr, 0, arr.length - 1, target);

        if (result != -1)
            System.out.println("Element " + target + " found at index " + result);
        else
            System.out.println("Element " + target + " not found in the array");

    }

}

This reusable function demonstrates modular programming, helping beginners understand how to structure code for repeated use without rewriting the search logic.

Program 5: Ternary Search for Floating-Point Numbers

Ternary Search can also work with floating-point numbers. This program demonstrates searching for decimal values in a sorted array.

public class TernarySearchFloat {

    public static int ternarySearch(float[] arr, float key) {

        int left = 0, right = arr.length - 1;

        while (left <= right) {

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

            if (arr[mid1] == key) return mid1;
            if (arr[mid2] == key) return mid2;

            if (key < arr[mid1])
                right = mid1 - 1;
            else if (key > arr[mid2])
                left = mid2 + 1;
            else {
                left = mid1 + 1;
                right = mid2 - 1;
            }

        }

        return -1;

    }

    public static void main(String[] args) {

        float[] arr = {0.5f, 1.2f, 2.3f, 3.8f, 4.6f, 5.9f};
        float key = 3.8f;

        int index = ternarySearch(arr, key);

        if (index != -1) {
            System.out.println("Element found at index " + index);
        } else {
            System.out.println("Element not found in the array");
        }

    }

}

This version highlights the versatility of Ternary Search. The algorithm works on decimal numbers as long as the array is sorted. Beginners can learn that the core logic remains the same, and small adaptations can extend an algorithm to different data types.

Program 6: Ternary Search with Error Handling

This program shows a robust implementation that safely handles empty arrays or cases where the target is not present.

public class TernarySearchSafe {

    static int ternarySearch(int[] arr, int left, int right, int target) {

        if (arr.length == 0) return -1;

        if (right >= left) {

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

            if (arr[mid1] == target) return mid1;
            if (arr[mid2] == target) return mid2;

            if (target < arr[mid1]) return ternarySearch(arr, left, mid1 - 1, target);
            else if (target > arr[mid2]) return ternarySearch(arr, mid2 + 1, right, target);
            else return ternarySearch(arr, mid1 + 1, mid2 - 1, target);

        }

        return -1;

    }

    public static void main(String[] args) {

        int[] arr = {7, 14, 21, 28, 35, 42};
        int target = 21;
        int result = ternarySearch(arr, 0, arr.length - 1, target);

        if (result != -1)
            System.out.println("Element " + target + " found at index " + result);
        else
            System.out.println("Element " + target + " not found in the array");

    }

}

Error handling ensures that the algorithm is safe for empty arrays or absent targets, teaching beginners how to write robust, real-world-ready code alongside algorithmic logic.

Frequently Asked Questions (FAQ)

Ternary Search is a useful 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 find elements in sorted arrays more efficiently by splitting the search space into three parts.

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

Q3: Is Ternary Search faster than binary search?
It may reduce comparisons slightly, but binary search is usually simpler and faster for most practical datasets.

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

Q5: Why should beginners learn Ternary Search?
It teaches divide-and-conquer techniques, recursion, iterative logic, and efficient array searching in a clear and structured way.

Conclusion

Ternary Search is a powerful and educational algorithm for efficiently searching sorted arrays. By implementing it in Java using recursive, iterative, reusable, and safe approaches, beginners can strengthen their understanding of divide-and-conquer strategies, recursion, loops, and error handling.

Practicing these programs helps beginners learn not only the algorithm but also good coding practices such as modularity and robustness. Starting with simple examples, experimenting with different approaches, and handling edge cases will build confidence and prepare learners for more advanced algorithmic challenges in Java.

Scroll to Top