In this tutorial, we will be discussing a program to count smaller elements in sorted array in C++.
In this we will be given a number and our task is to count all the elements present in the sorted array which are smaller than the given number.
Example
#include <bits/stdc++.h>
using namespace std;
int countSmaller(int arr[], int n, int x){
return upper_bound(arr, arr+n, x) - arr;
}
int main(){
int arr[] = { 10, 20, 30, 40, 50 };
int n = sizeof(arr)/sizeof(arr[0]);
cout << countSmaller(arr, n, 45) << endl;
cout << countSmaller(arr, n, 55) << endl;
cout << countSmaller(arr, n, 4) << endl;
return 0;
}Output
4 5 0