|
| 1 | +""" |
| 2 | +Ternary Search in Python by @Tr-Jono |
| 3 | +
|
| 4 | +Algorithm: (list must be sorted) |
| 5 | +1. If list is empty, return False. |
| 6 | +1. Assign m1 and m2 s.t. they are the boundaries when the list is cut into thirds. |
| 7 | +2. If list[m1] or list[m2] is the desired value, return True. |
| 8 | +3. Else, use the same algorithm on: |
| 9 | + a. The first third of the list, if the desired value is smaller than list[m1], else |
| 10 | + b. The last third of the list, if the desired value is larger than list[m2], else |
| 11 | + c. The middle third of the list. |
| 12 | +
|
| 13 | +Time Complexity: O(log3 n) |
| 14 | +""" |
| 15 | + |
| 16 | + |
| 17 | +def ternary_search(a, target): |
| 18 | + """Ternary search if `target` is in `a`.""" |
| 19 | + if not a: |
| 20 | + return False |
| 21 | + m1 = len(a) // 3 |
| 22 | + m2 = len(a) - m1 - 1 |
| 23 | + if a[m1] == target or a[m2] == target: |
| 24 | + return True |
| 25 | + if target < a[m1]: |
| 26 | + return ternary_search(a[:m1], target) |
| 27 | + elif target > a[m2]: |
| 28 | + return ternary_search(a[m2 + 1:], target) |
| 29 | + else: |
| 30 | + return ternary_search(a[m1 + 1:m2], target) |
| 31 | + |
| 32 | + |
| 33 | +def main(): |
| 34 | + print("ternary_search([1, 2, 3], 5):", ternary_search([1, 2, 3], 5)) |
| 35 | + print("ternary_search([3, 5, 7, 9, 11, 13, 15], 5):", ternary_search([3, 5, 7, 9, 11, 13, 15], 5)) |
| 36 | + print("ternary_search([1, 2, 3, 4, 6, 7, 8, 9, 10], 5):", ternary_search([1, 2, 3, 4, 6, 7, 8, 9, 10], 5)) |
| 37 | + |
| 38 | + |
| 39 | +if __name__ == "__main__": |
| 40 | + main() |
0 commit comments