Count smaller elements in sorted array in C++


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

 Live Demo

#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

Updated on: 16-Mar-2020

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements