2024-05-16 11:39:16 +00:00
|
|
|
|
2024-05-16 11:56:17 +00:00
|
|
|
def binary_search(arr, target):
|
|
|
|
low = 0
|
|
|
|
high = len(arr) - 1
|
2024-05-16 11:39:16 +00:00
|
|
|
|
2024-05-16 11:56:17 +00:00
|
|
|
while low <= high:
|
|
|
|
mid = (low + high) // 2
|
|
|
|
mid_val = arr[mid]
|
2024-05-16 11:39:16 +00:00
|
|
|
|
2024-05-16 11:56:17 +00:00
|
|
|
if mid_val == target:
|
2024-05-16 11:39:16 +00:00
|
|
|
return mid
|
2024-05-16 11:56:17 +00:00
|
|
|
elif mid_val < target:
|
|
|
|
low = mid + 1
|
2024-05-16 11:39:16 +00:00
|
|
|
else:
|
2024-05-16 11:56:17 +00:00
|
|
|
high = mid - 1
|
2024-05-16 11:39:16 +00:00
|
|
|
|
2024-05-16 11:56:17 +00:00
|
|
|
return -1
|
2024-05-16 11:39:16 +00:00
|
|
|
|
2024-05-16 11:56:17 +00:00
|
|
|
def main():
|
|
|
|
arr = list(map(int, input("Enter the array elements: ").split()))
|
|
|
|
arr.sort()
|
|
|
|
target = int(input("Enter the number to search for: "))
|
2024-05-16 11:39:16 +00:00
|
|
|
|
2024-05-16 11:56:17 +00:00
|
|
|
index = binary_search(arr, target)
|
|
|
|
if index != -1:
|
|
|
|
print(f"{target} found at index {index}.")
|
2024-05-16 11:39:16 +00:00
|
|
|
else:
|
2024-05-16 11:56:17 +00:00
|
|
|
print(f"{target} not found.")
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|