Program to demonstrate the use of Binary Search to search a given element in a sorted array in ascending order.
Question
Program to demonstrate the use of Binary Search to search a given element in a sorted array in ascending order.
Solution
Sure, here is a simple Python program that demonstrates the use of Binary Search to search a given element in a sorted array in ascending order.
def binary_search(arr, low, high, x):
# Check base case
if high >= low:
mid = (high + low) // 2
# If element is present at the middle itself
if arr[mid] == x:
return mid
# If element is smaller than mid, then it can only
# be present in left subarray
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
# Else the element can only be present in right subarray
else:
return binary_search(arr, mid + 1, high, x)
else:
# Element is not present in array
return -1
# Test array
arr = [2, 3, 4, 10, 40]
x = 10
# Function call
result = binary_search(arr, 0, len(arr)-1, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
This program first defines a function binary_search
that takes a sorted array arr
, the lowest index low
, the highest index high
, and the element x
to be searched. It then checks if the element is present at the middle of the array. If it is, it returns the index. If the element is smaller than the middle element, it performs the search on the left subarray. If the element is larger, it performs the search on the right subarray. If the element is not found, it returns -1. The program then tests this function with a test array and a test element.
Similar Questions
In a binary search, the elements of the array must be in which order?Group of answer choicesAll options are correctAscending orderRandom orderDescending order
Suppose following numbers are sorted in an array A:32,51,26,84,63,21,11,54Using Binary search find the location of item 26,11 and 99.Answer text
If a list of elements is already sorted in ascending order, how many comparisons are needed in the worst-case scenario to find an element using Binary Search?
What is the maximum number of comparisons required to find an element in a sorted array of size 31 using Binary Search?4567
In a sorted array, which search algorithm is more efficient than linear search?*1 pointA. Binary SearchB. Quick SearchC. Bubble SortD. Merge Sort
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.