diff --git a/searches/binary_search.py b/searches/binary_search.py index bec87b3c5aec..5c98995ba90d 100644 --- a/searches/binary_search.py +++ b/searches/binary_search.py @@ -194,6 +194,8 @@ def binary_search(sorted_collection: list[int], item: int) -> int: 4 >>> binary_search([0, 5, 7, 10, 15], 5) 1 + >>> binary_search([1, 2, 2, 2, 3], 2) + 1 >>> binary_search([0, 5, 7, 10, 15], 6) -1 """ @@ -201,17 +203,19 @@ def binary_search(sorted_collection: list[int], item: int) -> int: raise ValueError("sorted_collection must be sorted in ascending order") left = 0 right = len(sorted_collection) - 1 + result = -1 while left <= right: midpoint = left + (right - left) // 2 current_item = sorted_collection[midpoint] if current_item == item: - return midpoint + result = midpoint + right = midpoint - 1 elif item < current_item: right = midpoint - 1 else: left = midpoint + 1 - return -1 + return result def binary_search_std_lib(sorted_collection: list[int], item: int) -> int: