// C++ program to implement recursive Binary Search
#include <bits/stdc++.h>
using namespace std;
int binarySearch(int A[], int n, int data)
{
int l, r, mid;
l = 0;
r = n - 1;
mid = (l + r) / 2;
while (l <= r)
{
// int mid = l + (r - l) / 2;
if (data == A[mid])
{
return mid;
}
else if (data >= A[mid])
{
l = mid + 1;
}
else
{
r = mid - 1;
}
mid = (l + r) / 2;
}
return -1;
}
int main()
{
int arr[] = {2, 3, 4, 10, 40};
int n = 5;
int x = 10;
int result = binarySearch(arr, n, x);
if (result == -1)
{
cout << " Number is not found ";
}
else
{
cout << " Number found in index: " << result;
}
return 0;
}
O
Output
Element is present at index 3
0 Comments