Skip to content

Commit 523cc0e

Browse files
authored
Improve sorted input validation in binary search
1 parent 2c15b8c commit 523cc0e

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

searches/binary_search.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -198,8 +198,11 @@ 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):
202-
raise ValueError("sorted_collection must be sorted in ascending order")
201+
if any(
202+
sorted_collection[i] > sorted_collection[i + 1]
203+
for i in range(len(sorted_collection) - 1)
204+
):
205+
raise ValueError("sorted_collection must be sorted in ascending order")
203206
left = 0
204207
right = len(sorted_collection) - 1
205208

0 commit comments

Comments
 (0)