Pure implementation of binary search algorithm in Python by recursion Be careful collection must be sorted, otherwise result will be unpredictable First recursion should be started with left=0 and right=(len(sorted_collection)-1) :param sorted_collection: some sorted collection wit
(sorted_collection, item, left, right)
| 86 | return None |
| 87 | |
| 88 | def binary_search_by_recursion(sorted_collection, item, left, right): |
| 89 | |
| 90 | """Pure implementation of binary search algorithm in Python by recursion |
| 91 | |
| 92 | Be careful collection must be sorted, otherwise result will be |
| 93 | unpredictable |
| 94 | First recursion should be started with left=0 and right=(len(sorted_collection)-1) |
| 95 | |
| 96 | :param sorted_collection: some sorted collection with comparable items |
| 97 | :param item: item value to search |
| 98 | :return: index of found item or None if item is not found |
| 99 | |
| 100 | Examples: |
| 101 | >>> binary_search_std_lib([0, 5, 7, 10, 15], 0) |
| 102 | 0 |
| 103 | |
| 104 | >>> binary_search_std_lib([0, 5, 7, 10, 15], 15) |
| 105 | 4 |
| 106 | |
| 107 | >>> binary_search_std_lib([0, 5, 7, 10, 15], 5) |
| 108 | 1 |
| 109 | |
| 110 | >>> binary_search_std_lib([0, 5, 7, 10, 15], 6) |
| 111 | |
| 112 | """ |
| 113 | if (right < left): |
| 114 | return None |
| 115 | |
| 116 | midpoint = left + (right - left) // 2 |
| 117 | |
| 118 | if sorted_collection[midpoint] == item: |
| 119 | return midpoint |
| 120 | elif sorted_collection[midpoint] > item: |
| 121 | return binary_search_by_recursion(sorted_collection, item, left, midpoint-1) |
| 122 | else: |
| 123 | return binary_search_by_recursion(sorted_collection, item, midpoint+1, right) |
| 124 | |
| 125 | def __assert_sorted(collection): |
| 126 | """Check if collection is sorted, if not - raises :py:class:`ValueError` |
nothing calls this directly
no outgoing calls
no test coverage detected