An element ele of an array of size N, whose frequency of occurrence is more than N/2 i.e. the element that appears more than N/2 times in the array is known as the Majority Element.
This element occurs the maximum number of times and there is only one majority element in an array.
Example:
arr[] = {1, 5, 1, 2, 1, 1, 3, 1, 2, 1}
Majority element = 1
N = 10, occurrence frequency = 6
In this article, we will be creating a function in C/C++ to find the majority element of the array. The input to the function is an array arr[] and its size N.
The function will print the majority element if it exists otherwise print "No majority element exists".
Input:
arr[] = {1, 5, 1, 2, 1, 1, 3, 1, 2, 1}
N = 10
Output:
1
One method to find the majority element of an array is by using nested loops. The outer loop is used to loop over the elements of the array. And for each element of the array, we will count the number of equal valued elements using another array. And update the max frequency element. After the end of the loop, we will check if the frequency is greater than N/2. If yes, print the maximum frequency element otherwise print "No majority element exists".
Program to find the Majority Element of array
Output:
Approach 2:
Another method is Moore's Voting Algorithm also known as Boyer-Moore Majority Voting Algorithm is an algorithm to find the majority element of an array.
The idea is to loop over the array finding elements which has greatest occurrence frequency and then check if it is a majority number or not.
Algorithm :
Program to find majority element using Moore's Voting algorithm
Output: