@@ -80,6 +80,39 @@ def binary_search_std_lib(sorted_collection, item):
|
80 | 80 | return index
|
81 | 81 | return None
|
82 | 82 |
|
| 83 | +def binary_search_by_recursion(sorted_collection, item, left, right): |
| 84 | + |
| 85 | +"""Pure implementation of binary search algorithm in Python by recursion |
| 86 | +
|
| 87 | +Be careful collection must be sorted, otherwise result will be |
| 88 | +unpredictable |
| 89 | +First recursion should be started with left=0 and right=(len(sorted_collection)-1) |
| 90 | +
|
| 91 | +:param sorted_collection: some sorted collection with comparable items |
| 92 | +:param item: item value to search |
| 93 | +:return: index of found item or None if item is not found |
| 94 | +
|
| 95 | +Examples: |
| 96 | +>>> binary_search_std_lib([0, 5, 7, 10, 15], 0) |
| 97 | +0 |
| 98 | +
|
| 99 | +>>> binary_search_std_lib([0, 5, 7, 10, 15], 15) |
| 100 | +4 |
| 101 | +
|
| 102 | +>>> binary_search_std_lib([0, 5, 7, 10, 15], 5) |
| 103 | +1 |
| 104 | +
|
| 105 | +>>> binary_search_std_lib([0, 5, 7, 10, 15], 6) |
| 106 | +
|
| 107 | +""" |
| 108 | +midpoint = left + (right - left) // 2 |
| 109 | + |
| 110 | +if sorted_collection[midpoint] == item: |
| 111 | +return midpoint |
| 112 | +elif sorted_collection[midpoint] > item: |
| 113 | +return binary_search_by_recursion(sorted_collection, item, left, right-1) |
| 114 | +else: |
| 115 | +return binary_search_by_recursion(sorted_collection, item, left+1, right) |
83 | 116 |
|
84 | 117 | def __assert_sorted(collection):
|
85 | 118 | """Check if collection is sorted, if not - raises :py:class:`ValueError`
|
|
0 commit comments