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.

Examples:

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

4
5
0

Time Complexity : O(Log n)



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 contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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 contribute@geeksforgeeks.org to report any issue with the above content.