File tree 1 file changed +33
-0
lines changed
1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments