forked from recongamer/Hacktoberfest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
implement_upper_and_lower_bound.cpp
93 lines (79 loc) · 1.73 KB
/
implement_upper_and_lower_bound.cpp
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// implementation of upper_bound() and lower_bound() with help of binary search
// Time Complexitcy will be : O(log n)
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
// function to calculate lower_bound()
int lower_bound(vector<int> &v , int element)
{
int lo = 0 , hi = v.size() - 1;
int mid;
while(hi - lo > 1)
{
mid = (lo+hi)/2;
if(v[mid] < element)
{
lo = mid+1;
}
else
{
hi = mid;
}
}
if(v[lo]>=element) return lo;
if(v[hi]>=element) return hi;
return -1;
}
// funciton to calculate upper_bound()
int upper_bound(vector<int> &v , int element)
{
int lo = 0 , hi = v.size()-1 ;
int mid;
while(hi-lo>1)
{
mid = (lo+hi)/2;
if(v[mid] <= element)
{
lo = mid+1;
}
else
{
hi = mid;
}
}
if(v[lo]>element) return lo;
else if(v[hi]>element) return hi;
return -1;
}
int main()
{
int n,to_find,lower_index,upper_index;
cin>>n;
vector<int> arr(n);
//reading values of vector
for(int i=0 ; i<n ; ++i)
{
cin>>arr[i];
}
//you need to sort the vector/ array if you want to apply lower_bound() , upper_bound()
sort(arr.begin(),arr.end());
cout<<"Enter element to find : ";
cin>>to_find;
lower_index = lower_bound(arr,to_find); // function calling
if(lower_index == -1)
{
cout<<"Lower bound does not exists "<<endl;
}
else
{
cout<<"Found at : "<<lower_index << " " <<"and value at that index is : "<<arr[lower_index]<<endl;
}
upper_index = upper_bound(arr,to_find); // function calling
if(upper_index == -1)
cout<<"Upper bound does not exists"<<endl;
else
cout<<"Found at: "<<upper_index<<" and value at that index is : "<<arr[upper_index]<<endl;
return 0;
}
// we can also use inbuit function upper_bound() and lower_bound() to check our functions