Skip to content

Commit 5cf726a

Browse files
authored
Improve sorted input validation in binary search
1 parent 2c15b8c commit 5cf726a

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

searches/binary_search.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,10 @@ def binary_search(sorted_collection: list[int], item: int) -> int:
198198
>>> binary_search([0, 5, 7, 10, 15], 6)
199199
-1
200200
"""
201-
if list(sorted_collection) != sorted(sorted_collection):
201+
if any(
202+
sorted_collection[i] > sorted_collection[i + 1]
203+
for i in range(len(sorted_collection) - 1)
204+
):
202205
raise ValueError("sorted_collection must be sorted in ascending order")
203206
left = 0
204207
right = len(sorted_collection) - 1

0 commit comments

Comments
 (0)