Answered step by step
Verified Expert Solution
Question
1 Approved Answer
I have written a binary search in Python, using a while loop, to find an element and tell me which index it sits at in
I have written a binary search in Python, using a while loop, to find an element and tell me which index it sits at in an array. I also need to put in a counter to tell me how many iterations it has run. I am having trouble finding where to put this in the code.
NM X: 000 main.py + 1- def binary_search(array, x, low, high): 2- while (low high): 3 mid = low + (high low) 7/2 4. if array [mid] 5 return mid 6 - elif array[mid] > x: 7 return binary_search(array, x, low, mid-1) 8, else: 9 return binary_search(array, x, mid + 1, high) 10 - else: 11 return -1 12 array = [2, 3, 6, 9, 12, 15, 19] 13 X = 12 14 15 result = binary_search(array, x, 0, len(array)-1) 16 17, if result != -1: 18 print("Element is present at index " + str(result)) 19 - else: 20 print("Not found") Ln: 7, Col: 55 Run Share Command Line Arguments Element is present at index 4Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started