Python Script To Perform Binary Search
Python Script To Perform Binary Search
Python
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
if arr[mid] < x:
low = mid + 1
else:
return mid
return -1
result = binary_search(arr, x)
if result != -1:
print(f"The element is present at index {result}")
else:
print("The element is not present in array")
AI-generated code. Review and use carefully. More info on FAQ.
This script defines a function binary_search that takes an array arr and an element x as
input. The function returns the index of the element x in the array arr if it is present,
otherwise it returns -1. The function uses a while loop to perform binary search on the array.
The loop continues until the element is found or the search space is exhausted. The function
returns the index of the element if it is found, otherwise it returns -1.
To use this script, you can modify the arr and x variables to suit your needs.
The arr variable should be a sorted array of elements, and the x variable should be the
element you want to search for. You can then run the script to perform binary search on the
array and find the index of the element.