Count smaller elements in sorted array in C++
Last Updated :
30 Mar, 2018
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.
#include <bits/stdc++.h>
using namespace std;
int countSmaller( int arr[], int n, int x)
{
return upper_bound(arr, arr+n, x) - arr;
}
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)
Share your thoughts in the comments
Please Login to comment...