Given an array arr[] of size n, Find the majority element in that array (if it exists).
Example 1:
Input:
N=9
arr[] = {3, 3, 4, 2, 4, 4, 2, 4, 4}
Output: 4
Example 2:
Input:
N=5
arr[] = {1, 2, 3, 4, 5}
Output: 0
To find the majority element in an array (if it exists) , you can Follow these steps
1. Input:- The code takes an integer n as input, representing the size of the array, and an array of integers
arr of size n as input elements.
2. Initialization:- It initializes two variables, max_count and index, to keep track of the count of the current
candidate for the majority element and its index.
3. Outer Loop (i):- The outer loop iterates through each element of the array arr one by one. It starts with i =
0 and goes up to i = n-1.
4. Inner Loop (j):- For each element at index i, there is an inner loop that also iterates through the entire
array arr using another index j. This inner loop is used to count how many times the element at index i
appears in the entire array.
5. Counting:- For each pair of indices (i, j), if the elements at arr[i] and arr[j] are equal, it increments the
count variable. This inner loop essentially counts how many times the element at index i appears in the
array.
6. Updating the Majority Candidate:- After the inner loop completes for a particular element at index i, it
checks whether the count (the number of times the element appears) is greater than the current max_count. If
it is, it updates max_count to count, and it updates index to i. This step helps find the candidate for the
majority element.
7. Checking for Majority Element:- After the outer loop finishes, the code checks whether the max_count is
greater than n/2. If it is, it means the candidate element (arr[index]) appears more than n/2 times, and it
is considered the majority element. In this case, it prints the majority element.
No Majority Element:- If max_count is not greater than n/2, it means there is no majority element, and it
prints "No Such Element."