QUESTION DATED : 07/12/2024
(Question Code : QC24120700)
BUILD A PYTHON PROGRAM THAT LETS USER TO CREATE A LIST OF ITEMS AND THEN SEARCH FOR A SPECIFIC ITEM USING BINARY SEARCH .
ANSWER
a = []
while True:
i = input("Enter the value to add it to list(type stop when all values are added):")
if i.lower() == 'stop':
break
else:
a.append(i)
a.sort()
b = input("Enter the value to be searched:")
def binary_search(a,b):
low, high = 0, len(a) - 1
while low <= high:
mid = (low + high) // 2
if a[mid] == b:
return mid
elif a[mid] < b:
low = mid + 1
else:
high = mid - 1
return -1
result = binary_search(a, b)
if result != -1:
print(f"Element {b} found at index {result}")
else:
print("Element not found")
-----
No comments:
Post a Comment