// 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)
{
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;
}
// ********* BY STL -->easy way ****************
int binarysearch(vector<int> A, int data)
{
int l, r, mid;
l = 0;
r = A.size() - 1;
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;
}
}
return -1;
}
int main()
{
vector<int> arr{2, 3, 4, 10, 40};
int result = binarysearch(arr, 10);
if (result == -1)
{
cout << " Number is not found ";
}
else
{
cout << " Number found in index : " << result;
}
return 0;
}
Output
Element is present at index 3
0 Comments