Skip to content

Commit c09fe3d

Browse files
authored
Merge pull request deutranium#200 from ishita4416/patch-1
added recursive binary search
2 parents 870a753 + ec13a6f commit c09fe3d

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
// recursive binary search for a sorted array
4+
bool binse(int arr[],int l,int h,int x)
5+
{
6+
if(l>h)
7+
return -1;
8+
int mid=l+(h-l)/2; //causes (l+h)/2 overloading so l+(h-l)/2 is preferred
9+
if(arr[mid]==x)
10+
return mid;
11+
if(arr[mid]>x)
12+
return binse(arr,l,mid-1,x);
13+
else
14+
return binse(arr,mid+1,h,x);
15+
}
16+
int main() {
17+
int n;
18+
cin>>n;
19+
int arr[n];
20+
for(int i=0;i<n;i++)
21+
cin>>arr[i];
22+
int x;
23+
cin>>x;//number to be searched
24+
int l=0,h=n-1;//lower limit and higher limit
25+
int pos=binse(arr,l,h,x);
26+
if(pos>=0)
27+
cout<<"The element is found at "<<pos+1;
28+
else
29+
cout<<"The element was not found";
30+
return 0;
31+
}

0 commit comments

Comments
 (0)