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.

[sourcecode language=”CPP”]

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

}

[/sourcecode]

**Output:**

4 5 0

Time Complexity : O(Log n)

## Recommended Posts:

- Count of smaller or equal elements in sorted array
- Count elements smaller than or equal to x in a sorted matrix
- Count elements less than or equal to a given value in a sorted rotated array
- Count of only repeated element in a sorted array of consecutive elements
- Delete array elements which are smaller than next or become smaller
- Count smaller elements on right side using Set in C++ STL
- First strictly smaller element in a sorted array in Java
- Search equal, bigger or smaller in a sorted array in Java
- Count 1's in a sorted binary array
- Find the Rotation Count in Rotated Sorted array
- For each element in 1st array count elements less than or equal to it in 2nd array
- Number of elements smaller than root using preorder traversal of a BST
- Count elements such that there are exactly X elements with values greater than or equal to X
- Count pairs from two sorted matrices with given sum
- Count quadruples from four sorted arrays whose sum is equal to a given value x

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.