Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions maths/binary_search_iterative.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""
Binary Search (Iterative)
Time Complexity: O(log n)
Space Complexity: O(1)
"""


def binary_search(arr, target):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file maths/binary_search_iterative.py, please provide doctest for the function binary_search

Please provide return type hint for the function: binary_search. If the function does not return a value, please provide the type hint as: def function() -> None:

Please provide type hint for the parameter: arr

Please provide type hint for the parameter: target

left, right = 0, len(arr) - 1

while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1

return -1


if __name__ == "__main__":
arr = [1, 3, 5, 7, 9, 11]
target = 7
print(binary_search(arr, target))