Check For Majority Element

Majority Element
Majority Element: A majority element in an array A[] of size n is an element that appears more than n/2 times (and hence there is at most one such element).

Write a function which takes an array and emits the majority element (if it exists), otherwise prints NONE as follows:

       I/P : 1 2 2 3 4 2 3 2 2
       O/P : 2

       I/P : 4 4 2 2 2 6 1 4
       O/P : NONE

The basic solution is to have two loops and keep track of maximum count for all different elements. If maximum count becomes greater than n/2 then break the loops and return the element having maximum count. If maximum count doesn’t become more than n/2 then majority element doesn’t exist

#include<stdio.h>

int max(int a,int b)
{

if(a<=b)
return b;
else
return a;
}

main()
{

 int a[20],i,j,n,count,max_count=0;

  printf("Enter Number Of Element in Array:\n");
  scanf("%d",&n);

  printf("Read Array Element From User:");
   for(i=0;i<n;i++)
    {
      scanf("%d",&a[i]);
    }

    for(i=0;i<n-1;i++)
     {
      count=1;
      for(j=i+1;j<n;j++)
       {
        if(a[i]==a[j])
         count++;
       }
       max_count=max(max_count,count);
       if(max_count>n/2)
         {
         printf("Majority element '%d' present\n",a[i]);
         break;
         }
     
      }
    if(max_count<n/2)
    printf("None\n");
 
}

Related Posts