Skip to content

Commit d68708e

Browse files
author
Your Name
committed
fix: return first match in binary search
1 parent 6c04620 commit d68708e

1 file changed

Lines changed: 6 additions & 2 deletions

File tree

searches/binary_search.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -194,24 +194,28 @@ def binary_search(sorted_collection: list[int], item: int) -> int:
194194
4
195195
>>> binary_search([0, 5, 7, 10, 15], 5)
196196
1
197+
>>> binary_search([1, 2, 2, 2, 3], 2)
198+
1
197199
>>> binary_search([0, 5, 7, 10, 15], 6)
198200
-1
199201
"""
200202
if any(a > b for a, b in pairwise(sorted_collection)):
201203
raise ValueError("sorted_collection must be sorted in ascending order")
202204
left = 0
203205
right = len(sorted_collection) - 1
206+
result = -1
204207

205208
while left <= right:
206209
midpoint = left + (right - left) // 2
207210
current_item = sorted_collection[midpoint]
208211
if current_item == item:
209-
return midpoint
212+
result = midpoint
213+
right = midpoint - 1
210214
elif item < current_item:
211215
right = midpoint - 1
212216
else:
213217
left = midpoint + 1
214-
return -1
218+
return result
215219

216220

217221
def binary_search_std_lib(sorted_collection: list[int], item: int) -> int:

0 commit comments

Comments
 (0)