0% found this document useful (0 votes)
40 views

Python Script To Perform Binary Search

This Python script defines a binary_search function that takes an array and element as input and returns the index of the element if found using binary search, or -1 if not found. It uses a while loop to iteratively search halves of the array by comparing the middle element to the target. The script provides an example array and element to test the function, printing the index if found or a message if not found.

Uploaded by

Vongayi Kuchekwa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Python Script To Perform Binary Search

This Python script defines a binary_search function that takes an array and element as input and returns the index of the element if found using binary search, or -1 if not found. It uses a while loop to iteratively search halves of the array by comparing the middle element to the target. The script provides an example array and element to test the function, printing the index if found or a message if not found.

Uploaded by

Vongayi Kuchekwa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

Here is a Python script that performs binary search:

Python
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0

while low <= high:


mid = (high + low) // 2

if arr[mid] < x:
low = mid + 1

elif arr[mid] > x:


high = mid - 1

else:
return mid

return -1

arr = [2, 3, 4, 10, 40]


x = 10

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.

You might also like