Advertisements
Advertisements
Question
Write a program that takes as input a list of 10 integers and a key value and applies binary search to find whether the key is present in the list or not. If the key is present it should display the position of the key in the list otherwise it should print an appropriate message. Run the program for at least 3 different key values and note the results.
Answer in Brief
Advertisements
Solution
def binary_search(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
else:
return binary_search(arr, mid + 1, high, x)
else:
return -1
arr = [ 2, 3, 4, 10, 24, 34, 67, 99, 100, 133 ]
x = int(input("Enter the key to be searched: "))
result = binary_search(arr, 0, len(arr)-1, x)
if result != -1:
print("Element is present at position", str(result+1))
else:
print("Element is not present in array")shaalaa.com
Binary Search in Python
Is there an error in this question or solution?
