# 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.

`// 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*

*filter_none*

**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
- Delete array elements which are smaller than next or become smaller
- Count of only repeated element in a sorted array of consecutive elements
- First strictly smaller element in a sorted array in Java
- Count smaller elements on right side using Set in C++ STL
- Search equal, bigger or smaller in a sorted array in Java
- Count of strings in the first array which are smaller than every string in the second array
- Count 1's in a sorted binary array
- Find the Rotation Count in Rotated Sorted array
- Find the number of elements greater than k in a 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

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.