
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 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
Why use Recursion for Binary Search?
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.