Pure implementation of binary search algorithm in Python using recursion Be careful: the 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 sear
(
sorted_collection: list[int], item: int, left: int = 0, right: int = -1
)
| 17 | |
| 18 | |
| 19 | def binary_search_by_recursion( |
| 20 | sorted_collection: list[int], item: int, left: int = 0, right: int = -1 |
| 21 | ) -> int: |
| 22 | """Pure implementation of binary search algorithm in Python using recursion |
| 23 | |
| 24 | Be careful: the collection must be ascending sorted otherwise, the result will be |
| 25 | unpredictable. |
| 26 | |
| 27 | :param sorted_collection: some ascending sorted collection with comparable items |
| 28 | :param item: item value to search |
| 29 | :param left: starting index for the search |
| 30 | :param right: ending index for the search |
| 31 | :return: index of the found item or -1 if the item is not found |
| 32 | |
| 33 | Examples: |
| 34 | >>> binary_search_by_recursion([0, 5, 7, 10, 15], 0, 0, 4) |
| 35 | 0 |
| 36 | >>> binary_search_by_recursion([0, 5, 7, 10, 15], 15, 0, 4) |
| 37 | 4 |
| 38 | >>> binary_search_by_recursion([0, 5, 7, 10, 15], 5, 0, 4) |
| 39 | 1 |
| 40 | >>> binary_search_by_recursion([0, 5, 7, 10, 15], 6, 0, 4) |
| 41 | -1 |
| 42 | """ |
| 43 | if right < 0: |
| 44 | right = len(sorted_collection) - 1 |
| 45 | if list(sorted_collection) != sorted(sorted_collection): |
| 46 | raise ValueError("sorted_collection must be sorted in ascending order") |
| 47 | if right < left: |
| 48 | return -1 |
| 49 | |
| 50 | midpoint = left + (right - left) // 2 |
| 51 | |
| 52 | if sorted_collection[midpoint] == item: |
| 53 | return midpoint |
| 54 | elif sorted_collection[midpoint] > item: |
| 55 | return binary_search_by_recursion(sorted_collection, item, left, midpoint - 1) |
| 56 | else: |
| 57 | return binary_search_by_recursion(sorted_collection, item, midpoint + 1, right) |
| 58 | |
| 59 | |
| 60 | def exponential_search(sorted_collection: list[int], item: int) -> int: |
no outgoing calls
no test coverage detected