Skip to content

Commit a60efb5

Browse files
author
sharanabasava-05
committed
added time complexity to binary_search.py docstring
1 parent 33a8e0f commit a60efb5

1 file changed

Lines changed: 24 additions & 2 deletions

File tree

searches/binary_search.py

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,6 @@ def insort_right(
176176
"""
177177
sorted_collection.insert(bisect_right(sorted_collection, item, lo, hi), item)
178178

179-
180179
def binary_search(sorted_collection: list[int], item: int) -> int:
181180
"""Pure implementation of a binary search algorithm in Python
182181
@@ -187,6 +186,29 @@ def binary_search(sorted_collection: list[int], item: int) -> int:
187186
:param item: item value to search
188187
:return: index of the found item or -1 if the item is not found
189188
189+
Time Complexity:
190+
Best Case: O(1)
191+
The item is found at the middle index in the first comparison.
192+
193+
Average Case: O(log n)
194+
Search space is reduced by half in each iteration.
195+
196+
Worst Case: O(log n)
197+
The item is at the end or not present in the collection.
198+
199+
Space Complexity: O(1)
200+
- Uses constant extra memory.
201+
Args:
202+
sorted_collection (list[int]):
203+
Ascending sorted collection of comparable items.
204+
205+
item (int):
206+
Item value to search.
207+
Returns:
208+
int:
209+
Index of the found item,
210+
or -1 if the item is not found.
211+
190212
Examples:
191213
>>> binary_search([0, 5, 7, 10, 15], 0)
192214
0
@@ -211,7 +233,7 @@ def binary_search(sorted_collection: list[int], item: int) -> int:
211233
right = midpoint - 1
212234
else:
213235
left = midpoint + 1
214-
return -1
236+
return -1
215237

216238

217239
def binary_search_std_lib(sorted_collection: list[int], item: int) -> int:

0 commit comments

Comments
 (0)