@@ -178,42 +178,40 @@ def insort_right(
178
178
sorted_collection .insert (bisect_right (sorted_collection , item , lo , hi ), item )
179
179
180
180
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.
183
185
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`.
186
189
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
190
193
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.
200
196
"""
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
213
210
else :
214
- left = midpoint + 1
215
- return - 1
211
+ low = mid + 1
216
212
213
+ # Return -1 if element is not present in the list
214
+ return - 1
217
215
218
216
def binary_search_std_lib (sorted_collection : list [int ], item : int ) -> int :
219
217
"""Pure implementation of a binary search algorithm in Python using stdlib
0 commit comments