@@ -197,21 +197,28 @@ def binary_search(sorted_collection: list[int], item: int) -> int:
197197 1
198198 >>> binary_search([0, 5, 7, 10, 15], 6)
199199 -1
200+ >>> binary_search([1, 2, 2, 2, 3], 2)
201+ 2
202+ >>> binary_search([4, 4, 4, 4], 4)
203+ 1
200204 """
201205 if list (sorted_collection ) != sorted (sorted_collection ):
202206 raise ValueError ("sorted_collection must be sorted in ascending order" )
207+
203208 left = 0
204209 right = len (sorted_collection ) - 1
205210
206211 while left <= right :
207212 midpoint = left + (right - left ) // 2
208213 current_item = sorted_collection [midpoint ]
214+
209215 if current_item == item :
210- return midpoint
211- elif item < current_item :
212- right = midpoint - 1
213- else :
216+ return midpoint # correct handling even with duplicates
217+ elif current_item < item :
214218 left = midpoint + 1
219+ else :
220+ right = midpoint - 1
221+
215222 return - 1
216223
217224
@@ -234,12 +241,17 @@ def binary_search_std_lib(sorted_collection: list[int], item: int) -> int:
234241 1
235242 >>> binary_search_std_lib([0, 5, 7, 10, 15], 6)
236243 -1
244+ >>> binary_search_std_lib([1, 2, 2, 2, 3], 2)
245+ 1
246+ >>> binary_search_std_lib([4, 4, 4, 4], 4)
247+ 0
237248 """
238249 if list (sorted_collection ) != sorted (sorted_collection ):
239250 raise ValueError ("sorted_collection must be sorted in ascending order" )
251+
240252 index = bisect .bisect_left (sorted_collection , item )
241253 if index != len (sorted_collection ) and sorted_collection [index ] == item :
242- return index
254+ return index # bisect_left handles duplicates correctly
243255 return - 1
244256
245257
@@ -265,23 +277,30 @@ def binary_search_by_recursion(
265277 1
266278 >>> binary_search_by_recursion([0, 5, 7, 10, 15], 6, 0, 4)
267279 -1
280+ >>> binary_search_by_recursion([1, 2, 2, 2, 3], 2, 0, 4)
281+ 2
282+ >>> binary_search_by_recursion([4, 4, 4, 4], 4, 0, 3)
283+ 1
268284 """
269285 if right < 0 :
270286 right = len (sorted_collection ) - 1
287+
271288 if list (sorted_collection ) != sorted (sorted_collection ):
272289 raise ValueError ("sorted_collection must be sorted in ascending order" )
273- if right < left :
290+
291+ if left > right :
274292 return - 1
275293
276294 midpoint = left + (right - left ) // 2
295+ mid_value = sorted_collection [midpoint ]
277296
278- if sorted_collection [ midpoint ] == item :
279- return midpoint
280- elif sorted_collection [ midpoint ] > item :
297+ if mid_value == item :
298+ return midpoint # valid index even with duplicates
299+ elif mid_value > item :
281300 return binary_search_by_recursion (sorted_collection , item , left , midpoint - 1 )
282301 else :
283302 return binary_search_by_recursion (sorted_collection , item , midpoint + 1 , right )
284-
303+
285304
286305def exponential_search (sorted_collection : list [int ], item : int ) -> int :
287306 """Pure implementation of an exponential search algorithm in Python
0 commit comments