How to Perform Binary Search Using Recursion in Python

In this tutorial, we will learn "How to Perform Binary Search Using Recursion in Python". The main objective is to understand and implement binary search recursively. This guide will walk you step by step through the process, making it easier to follow and apply. By the end of this tutorial, you will have a solid understanding of how binary search works in Python, helping you strengthen your problem-solving abilities and improve your overall coding skills in data structure implementation.

This topic is straightforward and easy to understand. By following the instructions provided, you will be able to complete it with ease. The program will guide you step by step through the process of implementing binary search using recursion. So, let’s dive into the coding process and start implementing the solution to gain a deeper understanding of Binary Search in Python.

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. def binary_search(alist, start, end, key):
  2.     """Search key in alist[start... end - 1] recursively."""
  3.     if not start < end:
  4.         return -1
  5.  
  6.     mid = (start + end) // 2
  7.     if alist[mid] < key:
  8.         return binary_search(alist, mid + 1, end, key)
  9.     elif alist[mid] > key:
  10.         return binary_search(alist, start, mid, key)
  11.     else:
  12.         return mid
  13.  
  14.  
  15. while True:
  16.     print("\n========== Perform Binary Search Using Recursion ==========\n")
  17.  
  18.     # Input the sorted list
  19.     alist = input('Enter the sorted list of numbers (space-separated): ')
  20.     alist = [int(x) for x in alist.split()]
  21.     key = int(input('The number to search for: '))
  22.  
  23.     # Perform binary search
  24.     index = binary_search(alist, 0, len(alist), key)
  25.     if index < 0:
  26.         print(f'{key} was not found.')
  27.     else:
  28.         print(f'{key} was found at index {index}.')
  29.  
  30.     # Try Again Option
  31.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  32.     if opt == "no":
  33.         print("Exiting program...")
  34.         break
  35.     elif opt != "yes":
  36.         print("Invalid choice. Exiting program...")
  37.         break

This Python program allows users to perform a binary search on a sorted list using recursion. It defines a `binary_search` function that searches for a given number within a specified range of a list by repeatedly dividing the search interval in half. The program runs an interactive loop where the user inputs a sorted list and a target number, and it reports whether the number was found and its index. After each search, the user can choose to try again or exit.

Output:

There you have it we successfully created How to Perform Binary Search Using Recursion in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials