-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path18th_bs_recur.cpp
More file actions
36 lines (36 loc) · 819 Bytes
/
18th_bs_recur.cpp
File metadata and controls
36 lines (36 loc) · 819 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//implement binary search using recursion
#include <bits/stdc++.h>
using namespace std;
int binary_search(int arr[],int key,int high,int low=0)
{
int mid=(high+low)/2;
if(low<high)
{
if(arr[mid]==key)
return 1;
else if(arr[mid]<key)
return(arr,key,high,mid+1);
else if(arr[mid]>key)
return(arr,key,mid-1,low);
}
return 0;
}
int main()
{
int n;
cout<<"Enter number of elements in the array : ";
cin>>n;
cout<<"Enter elements in the array in a sorted manner : \n";
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int key;
cout<<"Enter key to search : ";
cin>>key;
if(binary_search(arr,key,n-1))
cout<<"Key : "<<key<<" is present.\n";
else
cout<<"Key : "<<key<<" is not present.\n";
}