Binary Search (Recursive) in C++
Binary Search Algorithm in C++ (Recursive Implementation).
1#include <iostream>2using namespace std;34int binarySearchRecursive(int arr[], int left, int right, int key) {5 if (left <= right) {6 int mid = left + (right - left) / 2;78 if (arr[mid] == key) {9 return mid; // Found at index mid10 }1112 if (arr[mid] > key) {13 return binarySearchRecursive(arr, left, mid - 1, key);14 }1516 return binarySearchRecursive(arr, mid + 1, right, key);17 }1819 return -1; // Not found20}2122int main() {23 int arr[] = {11, 12, 22, 25, 34, 64, 90};24 int n = sizeof(arr) / sizeof(arr[0]);25 int key;2627 cout << "Sorted array: ";28 for (int i = 0; i < n; i++) {29 cout << arr[i] << " ";30 }31 cout << endl;3233 cout << "Enter element to search: ";34 cin >> key;3536 int result = binarySearchRecursive(arr, 0, n - 1, key);3738 if (result != -1) {39 cout << "Element found at index: " << result << endl;40 } else {41 cout << "Element not found in array" << endl;42 }4344 return 0;45}
Output
Sorted array: 11 12 22 25 34 64 90 Enter element to search: 25 Element found at index: 3
What's going on
The program searches for an element in a sorted array using Binary Search (recursive version). For example:
The recursive version divides the problem into smaller subproblems by calling itself with a smaller search interval.
Header File Used
This header provides:
1#include <iostream>
Understanding Recursive Binary Search
Algorithm Concept
:
Visual Example
:
Array: [11, 12, 22, 25, 34, 64, 90]
Search for: 25
Call 1: binarySearch(arr, 0, 6, 25)
Example (searching for 34):
Call 1: binarySearch(arr, 0, 6, 34)
Call 2: binarySearch(arr, 4, 6, 34)
Call 3: binarySearch(arr, 4, 4, 34)
Function: binarySearchRecursive()
int binarySearchRecursive(int arr[], int left, int right, int key) {
if (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == key) {
}
if (arr[mid] > key) {
return binarySearchRecursive(arr, left, mid - 1, key);
}
return binarySearchRecursive(arr, mid + 1, right, key);
}
return -1; // Not found
}
1return mid; // Found at index mid
How it works
:
Step-by-Step Recursion
Base Case
:
Recursive Cases
:
Recursion Tree
(searching for 34):
binarySearch(arr, 0, 6, 34)
mid=3, arr[3]=25 < 34
→ binarySearch(arr, 4, 6, 34)
mid=5, arr[5]=64 > 34
→ binarySearch(arr, 4, 4, 34)
mid=4, arr[4]=34 == 34
→ return 4
Time and Space Complexity
Time Complexity
: O(log n)
Space Complexity
: O(log n)
When to Use Recursive Binary Search
Best For
:
Not Recommended For
:
Recursive vs Iterative
Recursive Advantages
:
Recursive Disadvantages
:
Iterative Advantages
:
Iterative Disadvantages
:
Important Considerations
Base Case
:
Recursive Calls
:
Stack Depth
:
return 0;
This ends the program successfully.