-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbsearchrecursion.cpp
More file actions
40 lines (40 loc) · 878 Bytes
/
bsearchrecursion.cpp
File metadata and controls
40 lines (40 loc) · 878 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
37
38
39
40
#include<bits/stdc++.h>
using namespace std;
int bsearch(vector <int> arr, int low, int high, int key)
{
if(low==high)
return -1;
int mid = (low + high)/2;
if(arr[mid] == key)
return mid;
if(arr[mid] > key)
return bsearch(arr,low,mid,key);
return bsearch(arr,mid+1,high,key);
}
int main()
{
int n;
vector <int > arr;
cout<< " Enter the number of elemnents : ";
cin>>n;
int temp;
cout << "Enter the elements in sorted order :"<<endl;
for(int i = 0;i<n;i++)
{
cin>>temp;
arr.push_back(temp);
}
cout << " Enter the key you want to search : ";
int key;
cin>>key ;
int x = bsearch(arr,0,n,key);
if(x == -1)
{
cout << "Element is not present "<<endl;
}
else
{
cout << "Element found at position "<< x + 1 << endl;
}
return 0;
}