Question
Asked By EnchantedMoonlight99 at
Answered By Expert
Jeremy
Expert · 2.6k answers · 2k people helped
Hello, please find below the Python code for modified binary_search.py with search implemented in recursion.
def binary_search(array, num):
return search(array, num, 0, len(array) - 1)
"""
search method implemented with recursion
"""
def search(array, num, min, max):
if max >= min:
mid = (min + max) // 2
if array[mid] == num:
return mid
elif array[mid] > num:
return search(array, num, min, mid - 1)
else:
return search(array, num, mid + 1, max)
else:
return -1
def main():
a = [i for i in range(-1, 10, 2)]
print(a)
for n in [1,0,-1,2,-2,4,5,6,7,-67,134]:
print("%5d index? %d" % (n, binary_search(a,n)))
main()
Just copy search method from above code, everything else is same.
Output Screengrab showing our search method is working fine with recursion :
If you have any doubt, let me know in comments. If not, please upvote the answer.
Thanks, Happy Learning!
🧑🏫 More Questions
👉 Interested in exploring further?
Chrome Extension
1. Search answers from our 90+ million questions database.
2. Get instantly AI Solutions powered by most advanced models like GPT-4, Bard, Math GPT, etc.
3. Enjoy one-stop access to millions of textbook solutions.
4. Chat with 50+ AI study mates to get personalized course studies.
5. Ask your questions simply with texts or screenshots everywhere.