Python Program to Implement Binary Search with Recursion

PythonServer Side ProgrammingProgramming

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 −


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)
         return binary_search(my_list, mid + 1, high, elem)
      return -1
my_list = [ 1, 9, 11, 21, 34, 54, 67, 90 ]
elem_to_search = 1
print("The list is")

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))
   print("Element not found!")


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


  • 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.
Published on 13-Mar-2021 10:04:40