Python Program to Implement Binary Search with Recursion


When it is required to implement binary search using recursion, a method can be defined, that checks if the index 'high' is greater than index 'low. Based on value present at 'mid' variable, the function is called again to search for the element.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

Below is a demonstration for the same −

Example

Live Demo

def binary_search(my_list, low, high, elem):
   if high >= low:
      mid = (high + low) // 2
      if my_list[mid] == elem:
         return mid
      elif my_list[mid] > elem:
         return binary_search(my_list, low, mid - 1, elem)
      else:
         return binary_search(my_list, mid + 1, high, elem)
   else:
      return -1
     
my_list = [ 1, 9, 11, 21, 34, 54, 67, 90 ]
elem_to_search = 1
print("The list is")
print(my_list)

my_result = binary_search(my_list,0,len(my_list)-1,elem_to_search)

if my_result != -1:
   print("Element found at index ", str(my_result))
else:
   print("Element not found!")

Output

The list is
[1, 9, 11, 21, 34, 54, 67, 90]
Element found at index 0

Explanation

  • A function named 'binary_search' is defined.
  • It takes the list, the 'low' variable, 'high' variable and the element to be searched as parameter.
  • Then, the variable 'mid' is assigned the average of 'high' and 'low' variables.
  • If the element at 'mid' is same as the element that needs to be searched for, it is returned.
  • Else, if the element at 'mid' position is greater than the element to be searched, the function is called again by passing different set of parameters.
  • Else if the element at 'mid' position is less than the element to be searched, the function is called again by passing a different set of parameters.
  • Now the list is defined, and the function is called by passing this list as parameter.
  • This operation's data is stored in a variable.
  • This variable is the output that is displayed on the console.

Updated on: 13-Mar-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements