Check for Majority Element in a sorted array in C++

C++Server Side ProgrammingProgramming

Suppose we have an array; we have to check whether given number x is the majority element of that array or not. The array is sorted. One element is said to be majority element, when it appears n/2 times in the array. Suppose an array is like {1, 2, 3, 3, 3, 3, 6}, x = 3, here the answer is true as 3 is the majority element of the array. There are four 3s. The size of the array is 7, so we can see 4 > 7/2.

We can count the occurrences of x in the array, and if the number is greater than n/2, the answer will be true, otherwise false.

Example

 Live Demo

#include <iostream>
#include <stack>
using namespace std;
bool isMajorityElement(int arr[], int n, int x){
   int freq = 0;
   for(int i = 0; i<n; i++){
      if(arr[i] == x )
         freq++;
      if(arr[i] > x)
         break;
   }
   return (freq > n/2);
}
int main() {
   int arr[] = {1, 2, 3, 3, 3, 3, 6};
   int n = sizeof(arr)/sizeof(arr[0]);
   int x = 3;
   if (isMajorityElement(arr, n, x))
      cout << x << " is the majority element of the array";
   else
      cout << x << " is not the majority element of the array";
}

Output

3 is the majority element of the array
raja
Published on 21-Oct-2019 17:48:05
Advertisements