|
| 1 | +''' |
| 2 | +Author: OMKAR PATHAK |
| 3 | +Created at: 26th August 2017 |
| 4 | +
|
| 5 | +Time complexity: O(logn) |
| 6 | +
|
| 7 | +More Info: https://en.wikipedia.org/wiki/Ternary_search |
| 8 | +''' |
| 9 | +from __future__ import division |
| 10 | +import inspect |
| 11 | + |
| 12 | +def search(_list, left, right, target): |
| 13 | + if right >= left: |
| 14 | + mid1 = (left + right) // 3 |
| 15 | + mid2 = (mid1 + right) // 3 |
| 16 | + |
| 17 | + # if target is present at mid1 |
| 18 | + if _list[mid1] == target: |
| 19 | + return mid1 |
| 20 | + |
| 21 | + # if target is present at mid2 |
| 22 | + if _list[mid2] == target: |
| 23 | + return mid2 |
| 24 | + |
| 25 | + # if target is present at left one-third |
| 26 | + if _list[mid1] > target: |
| 27 | + return search(_list, left, mid1 - 1, target) |
| 28 | + |
| 29 | + # if target is present at right one-third |
| 30 | + if _list[mid2] < target: |
| 31 | + return search(_list, mid2 + 1, right, target) |
| 32 | + |
| 33 | + # if target is present in the middle one-third |
| 34 | + return search(_list, mid1 + 1, mid2 - 1, target) |
| 35 | + |
| 36 | + return False |
| 37 | + |
| 38 | +def time_complexities(): |
| 39 | + """ |
| 40 | + Return information on functions |
| 41 | + time complexity |
| 42 | + :return: string |
| 43 | + """ |
| 44 | + return "Time complexity: O(logn)" |
| 45 | + |
| 46 | + |
| 47 | +def get_code(): |
| 48 | + """ |
| 49 | + easily retrieve the source code |
| 50 | + of the function |
| 51 | + :return: source code |
| 52 | + """ |
| 53 | + return inspect.getsource(search) |
0 commit comments