Get startedGet started for free

Binary search using recursion

In this exercise, you will implement the binary search algorithm you just learned using recursion. Recall that a recursive function refers to a function calling itself.

This exercise is part of the course

Data Structures and Algorithms in Python

View Course

Exercise instructions

  • Define the base case.
  • Check whether the search value equals the value in the middle.
  • Call the binary_search_recursive() function recursively on the left half of the list.
  • Call the binary_search_recursive() function recursively on the right half of the list.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

def binary_search_recursive(ordered_list, search_value):
  # Define the base case
  if ____(ordered_list) == 0:
    return False
  else:
    middle = len(ordered_list)//2
    # Check whether the search value equals the value in the middle
    if search_value == ____:
        return True
    elif search_value < ordered_list[middle]:
        # Call recursively with the left half of the list
        return ____(ordered_list[:middle], search_value)
    else:
        # Call recursively with the right half of the list
        return ____
  
print(binary_search_recursive([1,5,8,9,15,20,70,72], 5))
Edit and Run Code