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

Function binary_search_by_recursion

searches/binary_search.py:320–357  ·  view source on GitHub ↗

Pure implementation of a binary search algorithm in Python by recursion Be careful collection must be ascending sorted otherwise, the result will be unpredictable First recursion should be started with left=0 and right=(len(sorted_collection)-1) :param sorted_collection: some ascen

(
    sorted_collection: list[int], item: int, left: int = 0, right: int = -1
)

Source from the content-addressed store, hash-verified

318
319
320def binary_search_by_recursion(
321 sorted_collection: list[int], item: int, left: int = 0, right: int = -1
322) -> int:
323 """Pure implementation of a binary search algorithm in Python by recursion
324
325 Be careful collection must be ascending sorted otherwise, the result will be
326 unpredictable
327 First recursion should be started with left=0 and right=(len(sorted_collection)-1)
328
329 :param sorted_collection: some ascending sorted collection with comparable items
330 :param item: item value to search
331 :return: index of the found item or -1 if the item is not found
332
333 Examples:
334 >>> binary_search_by_recursion([0, 5, 7, 10, 15], 0, 0, 4)
335 0
336 >>> binary_search_by_recursion([0, 5, 7, 10, 15], 15, 0, 4)
337 4
338 >>> binary_search_by_recursion([0, 5, 7, 10, 15], 5, 0, 4)
339 1
340 >>> binary_search_by_recursion([0, 5, 7, 10, 15], 6, 0, 4)
341 -1
342 """
343 if right < 0:
344 right = len(sorted_collection) - 1
345 if list(sorted_collection) != sorted(sorted_collection):
346 raise ValueError("sorted_collection must be sorted in ascending order")
347 if right < left:
348 return -1
349
350 midpoint = left + (right - left) // 2
351
352 if sorted_collection[midpoint] == item:
353 return midpoint
354 elif sorted_collection[midpoint] > item:
355 return binary_search_by_recursion(sorted_collection, item, left, midpoint - 1)
356 else:
357 return binary_search_by_recursion(sorted_collection, item, midpoint + 1, right)
358
359
360def exponential_search(sorted_collection: list[int], item: int) -> int:

Callers 1

exponential_searchFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected