Python Program to Implement Binary Search with Recursion



The binary search algorithm is the fastest algorithm to search for an element in a sorted array. It works by dividing the array into two halves and checking if the target element is in the left or right half, thus reducing the search space by half with each iteration.

Binary Search Animation

Binary Search Using Recursion

The following are the steps to implement binary search using recursion:

  • Define a binSearch() function that accepts the array, the left index, the right index, and the target that you want to search.
  • Check if the left index becomes greater than the right index. If yes, return element not found.
  • Calculate the middle index of the array and compare the target with the middle element. Return the middle index if the target is found at the middle index.
  • If the target is greater than the middle element, call the binSearch() function by setting the left index as mid + 1 (i.e., search in the right half of the array).
  • If the target is less than the middle element, call the binSearch() function by setting the right index as mid - 1 (i.e., search in the left half of the array).

Python Program for Binary Search Using Recursion

The following example has a recursive function that searches for an element in a binary tree:

def binSearch(arr, left, right, target):
    if left > right:
        return -1
    mid = left + (right - left) // 2
    if arr[mid] == target:
        return mid
    elif arr[mid] < target:
        return binSearch(arr, mid + 1, right, target)
    else:
        return binSearch(arr, left, mid - 1, target)

arr = [2, 4, 6, 8, 10]
n = len(arr)
target = 6
print("Given array:", arr)
print("Target Element to search:", target)
result = binSearch(arr, 0, n - 1, target)
print("Element", target, "found at index:", result)

The output of the above code is as follows:

Given array: 2 4 6 8 10
Target Element to search: 6
Element 6 found at index: 2

Recursion is a divide and conquer technique that simplifies the implementation of binary search. It allows the algorithm to break down the problem into smaller subproblems, making it easier to understand and maintain.

But recursion can also lead to increased memory usage due to the recursion stack. Each recursive call adds a new layer to the stack, which can consume more memory. This can be a concern in the case of large arrays or deep recursion. In such cases, an iterative approach is preferred to avoid stack overflow errors. Check out our article on Iterative Binary Search for more details.

Farhan Muhamed
Farhan Muhamed

No Code Developer, Vibe Coder

Updated on: 2025-08-20T17:36:53+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements