Skip to content

Commit 905626d

Browse files
authored
Add iterative binary search implementation
Implement iterative binary search algorithm.
1 parent 3c88735 commit 905626d

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

maths/binary_search_iterative.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""
2+
Binary Search (Iterative)
3+
Time Complexity: O(log n)
4+
Space Complexity: O(1)
5+
"""
6+
7+
def binary_search(arr, target):
8+
left, right = 0, len(arr) - 1
9+
10+
while left <= right:
11+
mid = (left + right) // 2
12+
if arr[mid] == target:
13+
return mid
14+
elif arr[mid] < target:
15+
left = mid + 1
16+
else:
17+
right = mid - 1
18+
19+
return -1
20+
21+
22+
if __name__ == "__main__":
23+
arr = [1, 3, 5, 7, 9, 11]
24+
target = 7
25+
print(binary_search(arr, target))

0 commit comments

Comments
 (0)