Skip to content

Commit d75aa30

Browse files
author
OpenClaw Assistant
committed
Fix binary_search to return first occurrence with duplicates
When a sorted list contains duplicate values and searching for an item that appears multiple times, binary_search now returns the index of the first occurrence instead of any arbitrary occurrence. This fixes issue #13840 where binary search returned the last index of a matching element instead of the first.
1 parent 135c748 commit d75aa30

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

searches/binary_search.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -196,22 +196,26 @@ def binary_search(sorted_collection: list[int], item: int) -> int:
196196
1
197197
>>> binary_search([0, 5, 7, 10, 15], 6)
198198
-1
199+
>>> binary_search([1, 2, 2, 2, 3], 2)
200+
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 # Continue searching left for first occurrence
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)