Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a7928f5

Browse files
author
Mrinal Chauhan
committed
feat : added find majority element in array using Moore's Voting Algorithm
1 parent 55ff0ad commit a7928f5

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Moore Voting Algorithm to find the majority element in an array
3+
* Majority element is the one that appears more than n/2 times
4+
* geeksforgeeks: https://www.geeksforgeeks.org/boyer-moore-majority-voting-algorithm/
5+
* @param {Array} arr array of integers
6+
* @returns {Number} majority element or null if no majority exists
7+
*/
8+
const MooreVotingAlgorithm = (arr) => {
9+
let candidate = null;
10+
let count = 0;
11+
12+
// Phase 1: Finding the candidate
13+
for (let num of arr) {
14+
if (count === 0) {
15+
candidate = num;
16+
count = 1;
17+
} else if (num === candidate) {
18+
count++;
19+
} else {
20+
count--;
21+
}
22+
}
23+
24+
// Phase 2: Validate the candidate
25+
count = 0;
26+
for (let num of arr) {
27+
if (num === candidate) {
28+
count++;
29+
}
30+
}
31+
32+
return count > arr.length / 2 ? candidate : null;
33+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /