0% found this document useful (0 votes)
6 views2 pages

Daa Program 3

The document provides a C++ program that implements a recursive binary search algorithm using the Divide and Conquer strategy. It defines a class 'BinarySearch' with a method 'search' to find the index of a specified key in a sorted array. The program prompts the user for the number of elements, the sorted elements, and the key to search, then outputs the result of the search.

Uploaded by

RK
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Daa Program 3

The document provides a C++ program that implements a recursive binary search algorithm using the Divide and Conquer strategy. It defines a class 'BinarySearch' with a method 'search' to find the index of a specified key in a sorted array. The program prompts the user for the number of elements, the sorted elements, and the key to search, then outputs the result of the search.

Uploaded by

RK
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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

You might also like