Count smaller elements in sorted array in C++

Given a sorted array and a number x, count smaller elements than x in the given array.


Input : arr[] = {10, 20, 30, 40, 50}
            x = 45
Output : 4
There are 4 elements smaller than 45.

Input : arr[] = {10, 20, 30, 40, 50}
            x = 40
Output : 3
There are 3 elements smaller than 40.

We can use upper_bound() in C++ to quickly find the result. It returns iterator (or pointer) to first element which is greater than given number. If all elements smaller, then it returns size of array. If all elements are greater than it returns 0.





// CPP program to count smaller elements
// in an array.
#include <bits/stdc++.h>
using namespace std;
int countSmaller(int arr[], int n, int x)
   return upper_bound(arr, arr+n, x) - arr;
// Driver code
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;




Time Complexity : O(Log n)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.