MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / rec_ternary_search

Function rec_ternary_search

searches/ternary_search.py:112–155  ·  view source on GitHub ↗

Recursive method of the ternary search algorithm. >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] >>> rec_ternary_search(0, len(test_list), test_list, 3) -1 >>> rec_ternary_search(4, len(test_list), test_list, 42) 8 >>> rec_ternary_search(0, 2, [4, 5, 6, 7], 4) 0 >>

(left: int, right: int, array: list[int], target: int)

Source from the content-addressed store, hash-verified

110
111
112def rec_ternary_search(left: int, right: int, array: list[int], target: int) -> int:
113 """Recursive method of the ternary search algorithm.
114
115 >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42]
116 >>> rec_ternary_search(0, len(test_list), test_list, 3)
117 -1
118 >>> rec_ternary_search(4, len(test_list), test_list, 42)
119 8
120 >>> rec_ternary_search(0, 2, [4, 5, 6, 7], 4)
121 0
122 >>> rec_ternary_search(0, 3, [4, 5, 6, 7], -10)
123 -1
124 >>> rec_ternary_search(0, 1, [-18, 2], -18)
125 0
126 >>> rec_ternary_search(0, 1, [5], 5)
127 0
128 >>> rec_ternary_search(0, 2, ['a', 'c', 'd'], 'c')
129 1
130 >>> rec_ternary_search(0, 2, ['a', 'c', 'd'], 'f')
131 -1
132 >>> rec_ternary_search(0, 0, [], 1)
133 -1
134 >>> rec_ternary_search(0, 3, [.1, .4 , -.1], .1)
135 0
136 """
137 if left < right:
138 if right - left < precision:
139 return lin_search(left, right, array, target)
140 one_third = (left + right) // 3 + 1
141 two_third = 2 * (left + right) // 3 + 1
142
143 if array[one_third] == target:
144 return one_third
145 elif array[two_third] == target:
146 return two_third
147
148 elif target < array[one_third]:
149 return rec_ternary_search(left, one_third - 1, array, target)
150 elif array[two_third] < target:
151 return rec_ternary_search(two_third + 1, right, array, target)
152 else:
153 return rec_ternary_search(one_third + 1, two_third - 1, array, target)
154 else:
155 return -1
156
157
158if __name__ == "__main__":

Callers 1

ternary_search.pyFile · 0.85

Calls 1

lin_searchFunction · 0.85

Tested by

no test coverage detected