Skip to content

Commit 89d5908

Browse files
author
Andres Torres
committed
fix: return the correct index when duplicates in binary_search
1 parent ae68a78 commit 89d5908

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

searches/binary_search.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -202,17 +202,19 @@ def binary_search(sorted_collection: list[int], item: int) -> int:
202202
raise ValueError("sorted_collection must be sorted in ascending order")
203203
left = 0
204204
right = len(sorted_collection) - 1
205+
result = -1
205206

206207
while left <= right:
207208
midpoint = left + (right - left) // 2
208209
current_item = sorted_collection[midpoint]
209210
if current_item == item:
210-
return midpoint
211+
result = midpoint
212+
right = midpoint - 1
211213
elif item < current_item:
212214
right = midpoint - 1
213215
else:
214216
left = midpoint + 1
215-
return -1
217+
return result
216218

217219

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

0 commit comments

Comments
 (0)