Brute Force Approach
Count the occurrences of each element and check if any element appears more than n/2 times.
Syntax:
for (let i = 0; i < n; i++) {
//implementation
if (count > n / 2) {
return arr[i];
}
}
Example: Below is the implementation of the above approach
Javascript
function findMajority(arr) { const n = arr.length; for (let i = 0; i < n; i++) { let count = 0; for (let j = 0; j < n; j++) { if (arr[i] === arr[j]) { count++; } } if (count > n / 2) { return arr[i]; } } return null ; } const arr1 = [2, 2, 3, 4, 2, 2, 5]; console.log(findMajority(arr1)); |
Output
2
JavaScript Program for Finding the Majority Element of an Array
Finding the majority element in an array is a common problem in computer science and data analysis. The majority element in an array is the element that appears more than n/2 times, where n is the length of the array. In other words, it’s the element that occurs more frequently than any other element in the array.
Examples:
Input: arr=[2, 2, 3, 4, 2, 2, 5]
Output: 2
Explanation: 2 appears more than n/2 times
Input: arr=[2, 3, 3, 3, 2, 2, 3]
Output: 3
Explanation: 3 appears more than n/2 times
Table of Content
- Brute Force Approach:
- Sorting Approach:
- Boyer-Moore Voting Algorithm:
Contact Us