Skip to content

Commit db2ae86

Browse files
author
jd878
committed
Add detailed docstring with examples to binary_search
1 parent ca5b8c1 commit db2ae86

File tree

1 file changed

+22
-29
lines changed

1 file changed

+22
-29
lines changed

searches/binary_search.py

Lines changed: 22 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -178,43 +178,36 @@ def insort_right(
178178
sorted_collection.insert(bisect_right(sorted_collection, item, lo, hi), item)
179179

180180

181-
def binary_search(sorted_collection: list[int], item: int) -> int:
182-
"""Pure implementation of a binary search algorithm in Python
181+
def binary_search(arr: list[int], target: int) -> int:
182+
"""
183+
Perform binary search on a sorted list to find the index of a target value.
183184
184-
Be careful collection must be ascending sorted otherwise, the result will be
185-
unpredictable
185+
Args:
186+
arr (list[int]): A sorted list of integers.
187+
target (int): The value to search for in the list.
186188
187-
:param sorted_collection: some ascending sorted collection with comparable items
188-
:param item: item value to search
189-
:return: index of the found item or -1 if the item is not found
189+
Returns:
190+
int: The index of target in arr if found, otherwise -1.
190191
191-
Examples:
192-
>>> binary_search([0, 5, 7, 10, 15], 0)
193-
0
194-
>>> binary_search([0, 5, 7, 10, 15], 15)
195-
4
196-
>>> binary_search([0, 5, 7, 10, 15], 5)
197-
1
198-
>>> binary_search([0, 5, 7, 10, 15], 6)
199-
-1
192+
Example:
193+
>>> binary_search([1, 2, 3, 4, 5], 3)
194+
2
195+
>>> binary_search([1, 2, 3], 7)
196+
-1
200197
"""
201-
if list(sorted_collection) != sorted(sorted_collection):
202-
raise ValueError("sorted_collection must be sorted in ascending order")
203-
left = 0
204-
right = len(sorted_collection) - 1
205-
206-
while left <= right:
207-
midpoint = left + (right - left) // 2
208-
current_item = sorted_collection[midpoint]
209-
if current_item == item:
210-
return midpoint
211-
elif item < current_item:
212-
right = midpoint - 1
198+
low, high = 0, len(arr) - 1
199+
while low <= high:
200+
mid = (low + high) // 2
201+
if arr[mid] == target:
202+
return mid
203+
elif arr[mid] < target:
204+
low = mid + 1
213205
else:
214-
left = midpoint + 1
206+
high = mid - 1
215207
return -1
216208

217209

210+
218211
def binary_search_std_lib(sorted_collection: list[int], item: int) -> int:
219212
"""Pure implementation of a binary search algorithm in Python using stdlib
220213

0 commit comments

Comments
 (0)