Skip to content

Commit 57d417d

Browse files
Fix: binary_search returns first matcing index for array that contains duplicates (Fixes #13840)
1 parent af17867 commit 57d417d

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

searches/binary_search.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -202,17 +202,18 @@ 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-
205+
answer = -1
206206
while left <= right:
207207
midpoint = left + (right - left) // 2
208208
current_item = sorted_collection[midpoint]
209209
if current_item == item:
210-
return midpoint
210+
answer = midpoint
211+
right = midpoint - 1
211212
elif item < current_item:
212213
right = midpoint - 1
213214
else:
214215
left = midpoint + 1
215-
return -1
216+
return answer
216217

217218

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

0 commit comments

Comments
 (0)