-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmoore_Voting.cpp
More file actions
54 lines (47 loc) · 955 Bytes
/
moore_Voting.cpp
File metadata and controls
54 lines (47 loc) · 955 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
53
54
#include <bits/stdc++.h>
using namespace std;
int moore_voting_algo(vector<int> &vec)
{
// assuming the first element is the most occuring element
int candidate = vec[0];
int c = 1;
int len = vec.size();
// finding the candidate
for (int i = 0; i < len; i++)
{
if (vec[i] == candidate)
{
c++;
}
else
{
c--;
if (c == 0)
{
candidate = vec[i];
c = 1;
}
}
}
// candidate verification
int count = 0;
for (auto &num : vec)
{
if (num == candidate)
{
count++;
}
}
if (count > len / 2)
{
return candidate;
}
return -1;
}
int main()
{
vector<int> vec = {1, 1, 2, 3, 3, 3, 3};
int val = moore_voting_algo(vec);
cout << "Element occuring more the n/2 times in the array: " << val;
return 0;
}