- 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
Find element in a sorted array whose frequency is greater than or equal to n/2 in C++.
Consider we have an array with size n. This array is sorted. There is one element whose frequency is greater than or equal to n/2, where n is the number of elements in the array. So if the array is like [3, 4, 5, 5, 5], then the output will be 5.
If we closely observe these type of array, we can easily notice that the number whose frequency is greater than or equal to n/2, will be present at index n/2 also. So the element can be found at position n/2
Example
Source Code: #include<iostream> using namespace std; int higherFreq(int arr[], int n) { return arr[n / 2]; } int main() { int arr[] = { 1, 2, 3, 4 , 4, 4, 4, 4, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); cout << "The number " << higherFreq(arr, n) << " has occurred more than or equal to "<<n <<"/2 amount of times"; }
Output −
The number 4 has occurred more than or equal to 10/2 amount of times
Advertisements