M.Sc Python Programming Assignments
Assignment 11
Question:
Write a program to implement binary search to search the given element using a function.
Code:
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
# Example sorted list
sorted_list = [2, 4, 6, 8, 10, 12, 14, 16]
target = int(input("Enter the element to search: "))
index = binary_search(sorted_list, target)
if index != -1:
print(f"Element {target} found at index {index}.")
else:
print(f"Element {target} not found.")
Output:
Enter the element to search: 10
Element 10 found at index 4.