lower_bound() function implement

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

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

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

        if(a[mid] >= value)
            high = mid;
        else
            low = mid + 1;
    }

    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 = Lower_Bound(a, n-1, value);

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

    return 0;
}

Comments