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