How to write a C Program to Find Majority element of an array ?
Majority elements are those which number appears more than half of the array size.
Solution
/* Find Majority element of an array. Majority elements are those which number appears more than half of the array size.
Sample input: 2 2 3 4 2
Sample output: 2
Sample input: 3 4 3 7 8 9
Sample output: none
*/
#include<stdio.h>
int main(void)
{
int x,p,i,j;
printf("enter array size:\n");
scanf("%d",&x);
p=x/2;
int a[x];
for(i=0;i<x;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<x;i++)
{
int counter=0;
for(j=0;j<x;j++)
{
if(a[i]==a[j])
{
counter=counter+1;
}
}
if(counter>p)
{
printf("%d",a[i]);
break;
}
}
return 0;
}