-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbinary_search.py
More file actions
39 lines (31 loc) · 940 Bytes
/
binary_search.py
File metadata and controls
39 lines (31 loc) · 940 Bytes
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
def binary_search(arr, target):
"""
Perform binary search on a sorted array.
Args:
arr: A sorted list of elements
target: The element to search for
Returns:
Index of target if found, -1 otherwise
"""
left, right = 0, len(arr) - 1
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
def print_number(number):
"""Print the given number."""
print(f"The number is: {number}")
if __name__ == "__main__":
numbers = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
target = 7
result = binary_search(numbers, target)
print_number(target)
if result != -1:
print(f"Found {target} at index {result}")
else:
print(f"{target} not found in the array")