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

 Live Demo

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

Updated on: 19-Dec-2019

93 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements