Skip to content

Commit 6215fe1

Browse files
Aniket Kumar SinghAniket Kumar Singh
authored andcommitted
Fix binary search to return first occurrence
1 parent 6c04620 commit 6215fe1

1 file changed

Lines changed: 9 additions & 21 deletions

File tree

searches/binary_search.py

Lines changed: 9 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -178,40 +178,28 @@ def insort_right(
178178

179179

180180
def binary_search(sorted_collection: list[int], item: int) -> int:
181-
"""Pure implementation of a binary search algorithm in Python
182-
183-
Be careful collection must be ascending sorted otherwise, the result will be
184-
unpredictable
185-
186-
:param sorted_collection: some ascending sorted collection with comparable items
187-
:param item: item value to search
188-
:return: index of the found item or -1 if the item is not found
189-
190-
Examples:
191-
>>> binary_search([0, 5, 7, 10, 15], 0)
192-
0
193-
>>> binary_search([0, 5, 7, 10, 15], 15)
194-
4
195-
>>> binary_search([0, 5, 7, 10, 15], 5)
196-
1
197-
>>> binary_search([0, 5, 7, 10, 15], 6)
198-
-1
199-
"""
200181
if any(a > b for a, b in pairwise(sorted_collection)):
201182
raise ValueError("sorted_collection must be sorted in ascending order")
183+
202184
left = 0
203185
right = len(sorted_collection) - 1
186+
result = -1
204187

205188
while left <= right:
206189
midpoint = left + (right - left) // 2
207190
current_item = sorted_collection[midpoint]
191+
208192
if current_item == item:
209-
return midpoint
193+
result = midpoint
194+
right = midpoint - 1
195+
210196
elif item < current_item:
211197
right = midpoint - 1
198+
212199
else:
213200
left = midpoint + 1
214-
return -1
201+
202+
return result
215203

216204

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

0 commit comments

Comments
 (0)