Skip to content

Commit 1a16b1b

Browse files
Create binary_search-iterative.py
1 parent a71618f commit 1a16b1b

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

binary_search-iterative.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""
2+
https://en.wikipedia.org/wiki/Binary_search_algorithm
3+
4+
Binary Search Algorithm (Iterative)
5+
-----------------------------------
6+
Binary search is a search algorithm that finds the position of a target value
7+
within a sorted array. It compares the target value to the middle element of the
8+
array; if they are unequal, the half in which the target cannot lie is eliminated,
9+
and the search continues on the remaining half until it is successful.
10+
11+
Time Complexity: O(log n)
12+
Space Complexity: O(1)
13+
"""
14+
15+
from typing import List
16+
17+
18+
def binary_search_iterative(arr: List[int], target: int) -> int:
19+
"""
20+
Perform binary search on a sorted list to find the index of the target element.
21+
22+
Args:
23+
arr (List[int]): Sorted list of integers.
24+
target (int): The element to search for.
25+
26+
Returns:
27+
int: The index of `target` in `arr`, or -1 if not found.
28+
29+
Examples:
30+
>>> binary_search_iterative([1, 3, 5, 7, 9], 7)
31+
3
32+
>>> binary_search_iterative([1, 3, 5, 7, 9], 2)
33+
-1
34+
>>> binary_search_iterative([], 5)
35+
-1
36+
"""
37+
left, right = 0, len(arr) - 1
38+
while left <= right:
39+
mid = left + (right - left) // 2
40+
if arr[mid] == target:
41+
return mid
42+
if arr[mid] < target:
43+
left = mid + 1
44+
else:
45+
right = mid - 1
46+
return -1
47+
48+
49+
if __name__ == "__main__":
50+
import doctest
51+
52+
doctest.testmod()

0 commit comments

Comments
 (0)