3.
Write a program to implement the recursive binary search technique using Divide
and Conquer strategy.
#include <iostream>
using namespace std;
class BinarySearch
{
public:
// Recursive Binary Search Function
int search(int arr[], int low, int high, int key)
{
if (low <= high)
{
int mid = (low + high) / 2;
if (arr[mid] == key)
return mid;
else if (key < arr[mid])
return search(arr, low, mid - 1, key);
else
return search(arr, mid + 1, high, key);
}
return -1; // Element not found
}
};
int main()
{
BinarySearch bs;
int n, key, arr[100];
cout << "Enter number of elements: ";
cin >> n;
cout << "Enter sorted elements: ";
for (int i = 0; i < n; i++)
cin >> arr[i];
cout << "Enter element to search: ";
cin >> key;
int result = [Link](arr, 0, n - 1, key);
if (result != -1)
cout << "Element found at position: " << result + 1;
else
cout << "Element not found";
return 0;
}
Input:
Enter number of elements: 5
Enter sorted elements: 10 20 30 40 50
Enter element to search: 35
Output:
Element not found