Skip to content
Related Articles

Related Articles

Count smaller elements in sorted array in C++
  • Difficulty Level : Easy
  • Last Updated : 30 Mar, 2018
GeeksforGeeks - Summer Carnival Banner

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.




// 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;
}
Output:
4
5
0

Time Complexity : O(Log n)

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :