
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Number of Elements Greater Than K in a Sorted Array Using C++
In this problem, we are given an array arr[] consisting of N sorted integer values and an integer k. Our task is to Find the number of elements greater than k in a sorted array.
Let’s take an example to understand the problem,
Input
arr[] = {1, 2, 5, 7, 8, 9} k = 4
Output
4
Explanation
Elements greater than k = 4 are 5, 7, 8, 9
Solution Approach
A simple solution to the problem is by using a loop over the array from 0 to N. And then stop at the first element greater than k. Then count the number of values remaining.
Example
Program to illustrate the working of our solution
#include <iostream> using namespace std; int findGreaterCount(int arr[], int n, int k){ for(int i = 0; i < n; i++){ if(arr[i] > k) return (n - i); } return -1; } int main(){ int arr[] = { 1, 3, 5, 7, 7, 8, 12, 21}; int n = sizeof(arr) / sizeof(arr[0]); int k = 5; cout<<"The number of elements greater than k is "<<findGreaterCount(arr, n, k); return 0; }
Output
The number of elements greater than k is 5
The above code works well but the time complexity of the program is of the order O(N).
Another more efficient approach is using binary search to find the elements greater than k. And then return the count of greater elements.
Example
Program to illustrate the working of our solution
#include <iostream> using namespace std; int findGreaterCount(int arr[], int n, int k){ int s = 0; int e = n - 1; int firstGreterEle = n; while (s <= e) { int mid = s + (e - s) / 2; if (arr[mid] > k) { firstGreterEle = mid; e = mid - 1; } else s = mid + 1; } return (n - firstGreterEle); } int main(){ int arr[] = { 1, 3, 5, 7, 7, 8, 12, 21}; int n = sizeof(arr) / sizeof(arr[0]); int k = 5; cout<<"The number of elements greater than k is "<<findGreaterCount(arr, n, k); return 0; }
Output
The number of elements greater than k is 5
Advertisements