Lower & Upper Bound

Binary Search

Lower Bound

#include "bits/stdc++.h"
using namespace std;

int main()
{
    int n; cin>>n;
    int a[n];
    for(int i=0; i<n; i++) cin>>a[i];

    auto its = lower_bound(a, a+n, 5);
    cout<<*its;

}
input
=======
5
1 3 4 5 6

output
=======
5

when we need index (LB)

#include "bits/stdc++.h"
using namespace std;

int main()
{
    int n; cin>>n;
    int a[n];
    for(int i=0; i<n; i++) cin>>a[i];

    auto its = lower_bound(a, a+n, 5) - a;
    cout<<its;

}
input
========
5
1 3 4 5 6

output
========
3

if not exist the value in the array

#include "bits/stdc++.h"
using namespace std;

int main()
{
    int n; cin>>n;
    int a[n];
    for(int i=0; i<n; i++) cin>>a[i];

    auto its = lower_bound(a, a+n, 5);
    cout<<*its;

}
input
=======
5
1 3 4 6 7

output
=========
6      -->(which is return next value)

Upper Bound

#include "bits/stdc++.h"
using namespace std;

int main()
{
    int n; cin>>n;
    int a[n];
    for(int i=0; i<n; i++) cin>>a[i];

    auto its = upper_bound(a, a+n, 5);
    cout<<*its;

}
input
=======
5
1 3 4 6 7
output
========
6       --> (Always next value)