Boyer-Moore Voting Algorithm
This algorithm finds the majority element in linear time and constant space
Syntax:
let candidate = null;
let count = 0;
for (let num of arr) {
if (count === 0) {
candidate = num;
}
count += (num === candidate)
? 1 : -1;
}
return candidate;
Example: Below is the implementation of the above approach
Javascript
function findMajority(arr) { let candidate = null ; let count = 0; for (let num of arr) { if (count === 0) { candidate = num; } count += (num === candidate) ? 1 : -1; } return candidate; } const arr3 = [2, 2, 3, 4, 2, 2, 5]; console.log(findMajority(arr3)); |
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