-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMoore_Voting_Algorithm.cpp
More file actions
53 lines (40 loc) · 954 Bytes
/
Copy pathMoore_Voting_Algorithm.cpp
File metadata and controls
53 lines (40 loc) · 954 Bytes
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
#include <bits/stdc++.h>
using namespace std;
int MooreAlgorithm(int a[] , int n)
{
int result = 0;
int frequency = 0;
for(int i=0 ; i<n ; i++)
{
if(a[i] == a[result])
frequency++;
else
frequency--;
//as the frequency is 0 then move to the next index which is our current index(i)
if(frequency == 0)
{
result = i;
frequency = 1;
}
}
return a[result];
}
int main()
{
int n , majority=0;
cout<<"\nEnter size of array : ";
cin>>n;
int a[n];
cout<<"\nEnter array : "<<endl;
for(int i=0 ; i<n ; i++)
cin>>a[i];
int answer = MooreAlgorithm(a , n);
for(int i=0 ; i<n ; i++)
if(a[i] == answer)
majority++;
if(majority > (n/2))
cout<<"\nMajority Element is = "<<answer<<endl;
else
cout<<"\nNo majority element is present"<<endl;
return 0;
}