# include<stdio.h>
# define bool int
int findCandidate(int *, int);
bool isMajority(int *, int, int);
void printMajority(int a[], int size)
{
int cand = findCandidate(a, size);
if(isMajority(a, size, cand))
printf(" %d ", cand);
else
printf("NO Majority Element");
}
int findCandidate(int a[], int size)
{
int maj_index = 0, count = 1;
int i;
for(i = 1; i < size; i++)
{
if(a[maj_index] == a[i])
count++;
else
count--;
if(count == 0)
{
maj_index = i;
count = 1;
}
}
return a[maj_index];
}
bool isMajority(int a[], int size, int cand)
{
int i, count = 0;
for (i = 0; i < size; i++)
if(a[i] == cand)
count++;
if (count > size/2)
return 1;
else
return 0;
}
int main()
{
int a[] = {1, 3, 3, 1,1,1,2,3,1,2,1,1};
printMajority(a, 12);
getchar();
return 0;
}
IyBpbmNsdWRlPHN0ZGlvLmg+CiMgZGVmaW5lIGJvb2wgaW50CgppbnQgZmluZENhbmRpZGF0ZShpbnQgKiwgaW50KTsKYm9vbCBpc01ham9yaXR5KGludCAqLCBpbnQsIGludCk7Cgp2b2lkIHByaW50TWFqb3JpdHkoaW50IGFbXSwgaW50IHNpemUpCnsKaW50IGNhbmQgPSBmaW5kQ2FuZGlkYXRlKGEsIHNpemUpOwoKaWYoaXNNYWpvcml0eShhLCBzaXplLCBjYW5kKSkKcHJpbnRmKCIgJWQgIiwgY2FuZCk7CmVsc2UKcHJpbnRmKCJOTyBNYWpvcml0eSBFbGVtZW50Iik7Cn0KCmludCBmaW5kQ2FuZGlkYXRlKGludCBhW10sIGludCBzaXplKQp7CmludCBtYWpfaW5kZXggPSAwLCBjb3VudCA9IDE7CmludCBpOwpmb3IoaSA9IDE7IGkgPCBzaXplOyBpKyspCnsKaWYoYVttYWpfaW5kZXhdID09IGFbaV0pCmNvdW50Kys7CmVsc2UKY291bnQtLTsKaWYoY291bnQgPT0gMCkKewptYWpfaW5kZXggPSBpOwpjb3VudCA9IDE7Cn0KfQpyZXR1cm4gYVttYWpfaW5kZXhdOwp9Cgpib29sIGlzTWFqb3JpdHkoaW50IGFbXSwgaW50IHNpemUsIGludCBjYW5kKQp7CmludCBpLCBjb3VudCA9IDA7CmZvciAoaSA9IDA7IGkgPCBzaXplOyBpKyspCmlmKGFbaV0gPT0gY2FuZCkKY291bnQrKzsKaWYgKGNvdW50ID4gc2l6ZS8yKQpyZXR1cm4gMTsKZWxzZQpyZXR1cm4gMDsKfQoKaW50IG1haW4oKQp7CmludCBhW10gPSB7MSwgMywgMywgMSwxLDEsMiwzLDEsMiwxLDF9OwpwcmludE1ham9yaXR5KGEsIDEyKTsKZ2V0Y2hhcigpOwpyZXR1cm4gMDsKfQ==