Advertisements
Advertisements
Question
Write a function that takes a sorted list and a number as an argument. Search for the number in the sorted list using binary search.
Code Writing
Advertisements
Solution
Binary search compares the required number with the middle element and searches only the appropriate half of the sorted list.
def binary_search(data_list, number):
low = 0
high = len(data_list) - 1
while low <= high:
mid = (low + high) // 2
if data_list[mid] == number:
return mid + 1 # Return 1-based position
if data_list[mid] < number:
low = mid + 1
else:
high = mid - 1
return -1
numbers = [2, 6, 7, 10, 14, 15, 16, 19]
position = binary_search(numbers, 14)
if position == -1:
print("Element not found")
else:
print("Element found at position", position)
Element found at position 5
shaalaa.com
Is there an error in this question or solution?
