Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 6 additions & 14 deletions searches/binary_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,20 +198,12 @@ def binary_search(sorted_collection: list[int], item: int) -> int:
>>> binary_search([0, 5, 7, 10, 15], 6)
-1
"""
if list(sorted_collection) != sorted(sorted_collection):
raise ValueError("sorted_collection must be sorted in ascending order")
left = 0
right = len(sorted_collection) - 1

while left <= right:
midpoint = left + (right - left) // 2
current_item = sorted_collection[midpoint]
if current_item == item:
return midpoint
elif item < current_item:
right = midpoint - 1
else:
left = midpoint + 1
# Use bisect_left to find the leftmost position
index = bisect_left(sorted_collection, item)

# Check if the item exists at that position
if index != len(sorted_collection) and sorted_collection[index] == item:
return index
return -1


Expand Down