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

Function binary_search

searches/binary_search.py:180–214  ·  view source on GitHub ↗

Pure implementation of a binary search algorithm in Python Be careful collection must be ascending sorted otherwise, the result will be unpredictable :param sorted_collection: some ascending sorted collection with comparable items :param item: item value to search :return: inde

(sorted_collection: list[int], item: int)

Source from the content-addressed store, hash-verified

178
179
180def binary_search(sorted_collection: list[int], item: int) -> int:
181 """Pure implementation of a binary search algorithm in Python
182
183 Be careful collection must be ascending sorted otherwise, the result will be
184 unpredictable
185
186 :param sorted_collection: some ascending sorted collection with comparable items
187 :param item: item value to search
188 :return: index of the found item or -1 if the item is not found
189
190 Examples:
191 >>> binary_search([0, 5, 7, 10, 15], 0)
192 0
193 >>> binary_search([0, 5, 7, 10, 15], 15)
194 4
195 >>> binary_search([0, 5, 7, 10, 15], 5)
196 1
197 >>> binary_search([0, 5, 7, 10, 15], 6)
198 -1
199 """
200 if any(a > b for a, b in pairwise(sorted_collection)):
201 raise ValueError("sorted_collection must be sorted in ascending order")
202 left = 0
203 right = len(sorted_collection) - 1
204
205 while left <= right:
206 midpoint = left + (right - left) // 2
207 current_item = sorted_collection[midpoint]
208 if current_item == item:
209 return midpoint
210 elif item < current_item:
211 right = midpoint - 1
212 else:
213 left = midpoint + 1
214 return -1
215
216
217def binary_search_std_lib(sorted_collection: list[int], item: int) -> int:

Callers 1

binary_search.pyFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected