- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count smaller elements in sorted array in C++
In this tutorial, we will be discussing a program to count smaller elements in sorted array in C++.
In this we will be given a number and our task is to count all the elements present in the sorted array which are smaller than the given number.
Example
#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; }
Output
4 5 0
Advertisements