upper_bound() function implement

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

int Upper_Bound(int a[], int sz, int value)
{
    int low = 0, high = sz;

    while(low < high)
    {
        int mid = (low + high)/2;

        if(a[mid] <= value)
            low = mid + 1;

        else
            high = mid;
    }

    if(low <= sz && a[low] <= value)
        low++;

    return low;
}

int main()
{
    int n;

    cout << "Enter Array Size :: ";
    cin >> n;

    int a[n], value;

    cout << "Enter Ascending Order Array Element :: ";
    for(int i=0;i<n;i++)
        cin >> a[i];

    cout << "Enter Search Value :: ";
    cin >> value;

    int indx = Upper_Bound(a, n-1, value);

    if(indx >= n)
        cout << "Upper Bound Not Found." << "\n";
    else
        cout << "Upper Bound Found at " << indx << " index." << "\n";

    return 0;
}

Comments