0% found this document useful (0 votes)
5 views

binary_search_program

The document presents a C++ program that implements a recursive binary search algorithm to find an element in a sorted array. It prompts the user to input the size of the array, the elements, and the key to search for, then outputs the position of the key if found and the number of recursive calls made. Sample outputs demonstrate the program's functionality with various inputs.

Uploaded by

arjunssagar3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

binary_search_program

The document presents a C++ program that implements a recursive binary search algorithm to find an element in a sorted array. It prompts the user to input the size of the array, the elements, and the key to search for, then outputs the position of the key if found and the number of recursive calls made. Sample outputs demonstrate the program's functionality with various inputs.

Uploaded by

arjunssagar3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Recursive Binary Search Program

#include<iostream>
using namespace std;

int count = 0;

int binarysearch(int a[], int beg, int end, int key) {


if (beg > end)
return -1;

count++;
int mid = (beg + end) / 2;

if (a[mid] == key)
return mid;
else if (key > a[mid])
return binarysearch(a, mid + 1, end, key);
else
return binarysearch(a, beg, mid - 1, key);
}

int main() {
int a[50], beg, end, key, i, n, index = -1, mid;

cout << "Enter the size of element ";


cin >> n;

cout << "\nEnter the ascending or descending element in array ";


for (int i = 0; i < n; i++) {
cin >> a[i];
}

cout << "\nEnter the key element ";


cin >> key;

beg = 0;
end = n - 1;
index = binarysearch(a, beg, end, key);

if (index != -1) {
cout << "\nElement is found at " << index + 1 << " position";
} else {
cout << "\nElement is not found";
}

cout << "\nNumber of turns is " << count;


return 0;
}

Sample Outputs
Enter the size of element 5
enter the ascending or descending element in array
1
2
3
4
5

Enter the key element 3


Element is found at 3 position
number of turns is 1

Enter the size of element 10


enter the ascending or descending element in array
1
2
3
4
5
6
7
8
9
10

Enter the key element 10


Element is found at 10 position
number of turns is 4

Enter the size of element 5


enter the ascending or descending element in array
1
2
3
4
5

Enter the key element 6


Element is not found
number of turns is 3

You might also like