Question: Question 1: (in python) Input: [2, 3, 4, 10, 40] 10 (element to be searched) 1. def binary_search(arr, x) where arr is list and x

Question 1: (in python) Input: [2, 3, 4, 10, 40] 10 (element to be searched)

1. def binary_search(arr, x) where arr is list and x is the element to be search 2. Set the lower bound low to the first index of the array and the upper bound high to the last index of the array. 3. Calculate the middle index mid as the average of low and high. 4. Check if the value at the middle index arr[mid] is equal to the target value x. If it is, return the middle index mid. 5. If the target value x is greater than the value at the middle index arr[mid], set low to mid + 1 to search the right half of the array. 6. If the target value x is less than the value at the middle index arr[mid], set high to mid - 1 to search the left half of the array. 7. Repeat steps 2-5 until the target value x is found or the lower bound low is greater than the upper bound high. 8. If the target value x is not found, return -1. 9. Call this function in main() and print the index number at which the element is present in the list.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!