-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbinary_search.py
More file actions
93 lines (68 loc) · 2.41 KB
/
binary_search.py
File metadata and controls
93 lines (68 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
"""
Binary Search Algorithm
Binary Search is an efficient algorithm for finding an item from a sorted list.
It works by repeatedly dividing in half the portion of the list that could contain
the item, until narrowing down the possible locations to just one.
Time Complexity:
- Best Case: O(1) - element found at middle
- Average Case: O(log n)
- Worst Case: O(log n)
Space Complexity: O(1) - iterative, O(log n) - recursive
Note: Array must be sorted for binary search to work.
"""
def binary_search(arr, target):
"""
Searches for a target value in a sorted array using Binary Search (iterative).
Args:
arr: Sorted list of elements to search in
target: Value to search for
Returns:
Index of target if found, -1 otherwise
"""
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
# Check if target is present at mid
if arr[mid] == target:
return mid
# If target is greater, ignore left half
elif arr[mid] < target:
left = mid + 1
# If target is smaller, ignore right half
else:
right = mid - 1
return -1
def binary_search_recursive(arr, target, left=0, right=None):
"""
Searches for a target value in a sorted array using Binary Search (recursive).
Args:
arr: Sorted list of elements to search in
target: Value to search for
left: Left boundary of search space
right: Right boundary of search space
Returns:
Index of target if found, -1 otherwise
"""
if right is None:
right = len(arr) - 1
if left > right:
return -1
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search_recursive(arr, target, mid + 1, right)
else:
return binary_search_recursive(arr, target, left, mid - 1)
# Example usage
if __name__ == "__main__":
numbers = [11, 12, 22, 25, 34, 64, 90] # Must be sorted
target = 22
result = binary_search(numbers, target)
if result != -1:
print(f"Element {target} found at index {result}")
else:
print(f"Element {target} not found in the array")
# Recursive version
result_rec = binary_search_recursive(numbers, target)
print(f"Recursive search result: {result_rec}")