Skip to content

Commit 73fe695

Browse files
authored
MoreVoting Majority Algorithm.
Created in Java
1 parent d4f6b3d commit 73fe695

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

moreVoting.java

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
//Subscribed on YouTube by AMRITSARI KING. Don't have facebook id.
2+
3+
class MajorityElement
4+
{
5+
6+
void printMajority(int a[], int size)
7+
{
8+
9+
int cand = findCandidate(a, size);
10+
11+
12+
if (isMajority(a, size, cand))
13+
System.out.println(" " + cand + " ");
14+
else
15+
System.out.println("No Majority Element");
16+
}
17+
18+
int findCandidate(int a[], int size)
19+
{
20+
int maj_index = 0, count = 1;
21+
int i;
22+
for (i = 1; i < size; i++)
23+
{
24+
if (a[maj_index] == a[i])
25+
count++;
26+
else
27+
count--;
28+
if (count == 0)
29+
{
30+
maj_index = i;
31+
count = 1;
32+
}
33+
}
34+
return a[maj_index];
35+
}
36+
37+
=
38+
boolean isMajority(int a[], int size, int cand)
39+
{
40+
int i, count = 0;
41+
for (i = 0; i < size; i++)
42+
{
43+
if (a[i] == cand)
44+
count++;
45+
}
46+
if (count > size / 2)
47+
return true;
48+
else
49+
return false;
50+
}
51+
52+
53+
public static void main(String[] args)
54+
{
55+
MajorityElement majorelement = new MajorityElement();
56+
int a[] = new int[]{1, 3, 3, 1, 2};
57+
int size = a.length;
58+
majorelement.printMajority(a, size);
59+
}
60+
}

0 commit comments

Comments
 (0)