Skip to content

Moore's Voting Algorithm - Boyer-Moore Majority Voting Algorithm #1750

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
feat : added find majority element in array using Moore's Voting Algo…
…rithm
  • Loading branch information
Mrinal Chauhan committed Oct 23, 2024
commit a7928f50dd2a39b0941ac7e15061d65393d23a86
33 changes: 33 additions & 0 deletions Data-Structures/Array/MooreVotingAlgorithm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* Moore Voting Algorithm to find the majority element in an array
* Majority element is the one that appears more than n/2 times
* geeksforgeeks: https://www.geeksforgeeks.org/boyer-moore-majority-voting-algorithm/
* @param {Array} arr array of integers
* @returns {Number} majority element or null if no majority exists
*/
const MooreVotingAlgorithm = (arr) => {
let candidate = null;
let count = 0;

// Phase 1: Finding the candidate
for (let num of arr) {
if (count === 0) {
candidate = num;
count = 1;
} else if (num === candidate) {
count++;
} else {
count--;
}
}

// Phase 2: Validate the candidate
count = 0;
for (let num of arr) {
if (num === candidate) {
count++;
}
}

return count > arr.length / 2 ? candidate : null;
};