|
| 1 | +package com.search; |
| 2 | + |
| 3 | +/** |
| 4 | + * A ternary search algorithm is a technique in computer science for finding the minimum or maximum of a unimodal function |
| 5 | + * The algorithm determines either that the minimum or maximum cannot be in the first third of the domain |
| 6 | + * or that it cannot be in the last third of the domain, then repeats on the remaining third. |
| 7 | + * <p> |
| 8 | + * Worst-case performance Θ(log3(N)) |
| 9 | + * Best-case performance O(1) |
| 10 | + * Average performance Θ(log3(N)) |
| 11 | + * Worst-case space complexity O(1) |
| 12 | + */ |
| 13 | +public final class TernarySearch { |
| 14 | + |
| 15 | + /** |
| 16 | + * @param arr The **Sorted** array in which we will search the element. |
| 17 | + * @param value The value that we want to search for. |
| 18 | + * @return The index of the element if found. |
| 19 | + * Else returns -1. |
| 20 | + */ |
| 21 | + public static <T extends Comparable<T>> int find(T[] arr, T value) { |
| 22 | + return search(arr, value, 0, arr.length - 1); |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * @param arr The **Sorted** array in which we will search the element. |
| 27 | + * @param key The value that we want to search for. |
| 28 | + * @param start The starting index from which we will start Searching. |
| 29 | + * @param end The ending index till which we will Search. |
| 30 | + * @return Returns the index of the Element if found. |
| 31 | + * Else returns -1. |
| 32 | + */ |
| 33 | + private static <T extends Comparable<T>> int search(T[] arr, T key, int start, int end) { |
| 34 | + if (start > end) { |
| 35 | + return -1; |
| 36 | + } |
| 37 | + |
| 38 | + int mid1 = start + (end - start) / 3; |
| 39 | + int mid2 = start + 2 * (end - start) / 3; |
| 40 | + |
| 41 | + if (key.compareTo(arr[mid1]) == 0) { |
| 42 | + return mid1; |
| 43 | + } else if (key.compareTo(arr[mid2]) == 0) { |
| 44 | + return mid2; |
| 45 | + } |
| 46 | + else if (key.compareTo(arr[mid1]) < 0) { |
| 47 | + return search(arr, key, start, --mid1); |
| 48 | + } |
| 49 | + else if (key.compareTo(arr[mid2]) > 0) { |
| 50 | + return search(arr, key, ++mid2, end); |
| 51 | + } |
| 52 | + else { |
| 53 | + return search(arr, key, mid1, mid2); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | +} |
0 commit comments