-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMoore's Voting Algorithm.js
68 lines (54 loc) · 1.3 KB
/
Moore's Voting Algorithm.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Moore Voting Problem
/*
findCandidate(a[], size)
1. Initialize index and count of majority element
maj_index = 0, count = 1
2. Loop for i = 1 to size – 1
(a) If a[maj_index] == a[i]
count++
(b) Else
count--;
(c) If count == 0
maj_index = i;
count = 1
3. Return a[maj_index]
4. Now check if a[maj_index] appears more than n/2.
*/
// To check if an element occurs inside the array more than half of the array size of the array.
// Implemented by @angularboy on 30/11/2016
function checkMajority(array) {
var maj_index = 0; count =1;
for( var i =0 ; i< array.length; i++ ) {
if(array[i] == array[maj_index]) {
count ++;
}
else {
count--;
}
if (count == 0) {
maj_index = i;
count = 1;
}
}
function finalpass(pass) {
console.log(array.length);
var flag =0;
for( var j =0;j<array.length;j++) {
if(pass == array[j]) {
flag++;
}
}
if (flag > (array.length/2)) {
return 1;
}
else {
return 0;
}
}
if( finalpass(array[maj_index])) {
return array[maj_index];
}
else {
return "None";
}
}