From 6215fe1b2b0d2af536a714f864abb93d1bc709fb Mon Sep 17 00:00:00 2001 From: Aniket Kumar Singh Date: Sun, 14 Jun 2026 15:26:20 +0530 Subject: [PATCH] Fix binary search to return first occurrence --- searches/binary_search.py | 30 +++++++++--------------------- 1 file changed, 9 insertions(+), 21 deletions(-) diff --git a/searches/binary_search.py b/searches/binary_search.py index bec87b3c5aec..79ff5f187de7 100644 --- a/searches/binary_search.py +++ b/searches/binary_search.py @@ -178,40 +178,28 @@ def insort_right( def binary_search(sorted_collection: list[int], item: int) -> int: - """Pure implementation of a binary search algorithm in Python - - Be careful collection must be ascending sorted otherwise, the result will be - unpredictable - - :param sorted_collection: some ascending sorted collection with comparable items - :param item: item value to search - :return: index of the found item or -1 if the item is not found - - Examples: - >>> binary_search([0, 5, 7, 10, 15], 0) - 0 - >>> binary_search([0, 5, 7, 10, 15], 15) - 4 - >>> binary_search([0, 5, 7, 10, 15], 5) - 1 - >>> binary_search([0, 5, 7, 10, 15], 6) - -1 - """ if any(a > b for a, b in pairwise(sorted_collection)): raise ValueError("sorted_collection must be sorted in ascending order") + left = 0 right = len(sorted_collection) - 1 + result = -1 while left <= right: midpoint = left + (right - left) // 2 current_item = sorted_collection[midpoint] + if current_item == item: - return midpoint + result = midpoint + right = midpoint - 1 + elif item < current_item: right = midpoint - 1 + else: left = midpoint + 1 - return -1 + + return result def binary_search_std_lib(sorted_collection: list[int], item: int) -> int: