-
Notifications
You must be signed in to change notification settings - Fork 0
/
upperbound binary search.cpp
79 lines (67 loc) · 1.18 KB
/
upperbound binary search.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
///Binary Search
///Finding UpperBound
/*
Input:
6
3 6 4 5 2 1
4
Output:
After Sort = 1 2 3 4 5 6
Index = 4 Value = 5
*/
/// GitHub UserName: \[aanafiu]
#include<bits/stdc++.h>
using namespace std;
int upper_bounds( vector<int> &v, int find_element)
{
int low = 0, high = v.size()-1, mid;
while(high-low > 1)
{
mid = (high+low)/2;
if(find_element >= v[mid] )
{
low = mid+1;
}
else
{
high = mid;
}
}
if(v[low] > find_element)
{
return low;
}
if(v[high] > find_element)
{
return high;
}
return -1;
}
int main()
{
int len;
cin >> len;
vector <int> v(len);
for(int i=0; i<len; i++)
{
cin >> v[i];
}
int find_elem;
cin >> find_elem;
sort(v.begin(),v.end());
cout << "After Sort = ";
for(auto elem : v)
{
cout << elem << " ";
}
cout << "\n";
int upperBoundIndex = upper_bounds( v, find_elem);
if(upperBoundIndex == -1)
{
cout << "Not Found\n";
}
else
{
cout << "Index = " << upperBoundIndex << " Value = " << v[upperBoundIndex] << endl;
}
}