-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmajority-voting-algorithm.cpp
65 lines (50 loc) · 1.23 KB
/
majority-voting-algorithm.cpp
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
// C++ Program for finding out
// majority element in an array
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
/* Function to find the candidate for Majority */
int findCandidate(int a[], int size) {
int maj_index = 0, count = 1;
for (int i = 1; i < size; i++) {
if (a[maj_index] == a[i])
count++;
else
count--;
if (count == 0) {
maj_index = i;
count = 1;
}
std::cout << a[i] << " " << maj_index <<" | ";
}
std::cout << std::endl;
return a[maj_index];
}
/* Function to check if the candidate
occurs more than n/2 times */
bool isMajority(int a[], int size, int cand) {
int count = 0;
for (int i = 0; i < size; i++)
if (a[i] == cand)
count++;
if (count > size / 4)
return 1;
else
return 0;
}
/* Function to print Majority Element */
void printMajority(int a[], int size) {
/* Find the candidate for Majority*/
int cand = findCandidate(a, size);
/* Print the candidate if it is Majority*/
if (isMajority(a, size, cand))
cout << " " << cand << " ";
else
cout << "No Majority Element";
}
int main() {
int a[] = {1, 3, 3, 1, 2, 4, 3, 3, 3, 6, 6,6};
int size = (sizeof(a)) / sizeof(a[0]);
printMajority(a, size);
return 0;
}