Friday, 21 October 2016

C++ Program To Find Element That Appears More Than N/2 Times.

Problem :- A Majority Element In An Array A[] of Size N Is An Element That Appears More Than N/2 (and hence there is at most one such element). Times. Write a Function Which Takes An Array And Emits The Majority Element (if it exists), Otherwise Prints NONE .

Logic :- We Need to print the Element Which repeat more than N/2 time's example if the size of array is 9 than number should be repeated at-least 5 times 
Let Take A Array 
Size =9
Array Element is 1 1 2 3 1 5 1 1 6

Now N/2 times should be 5 ,So here only 1 is a element only repeated more than N/2.
So Candidate Key is 1. 

Solution :-

#include<bits/stdc++.h>
using namespace std;

int majority(int a[],int size)
{
    int maj_index=0,count=1;
   
for(int i=1;i<size;i++)
    {
      if(a[i]==a[maj_index])
        count++;
    else
      count--;
    if(count==0)
    {
      maj_index=i;
      count=1;
    }
    }
    return a[maj_index];
}
bool ismejority(int a[],int size,int cand)
{
  int count=0;
 
for(int i=0;i<size;i++)
  {
    if(a[i]==cand)
      count++;
  }
  if(count>size/2)
    return 1;
  else
    return 0;
}
int main()
{
  int a[100],i,n;
    
cout<<"Enter The Size of An Array\n";
    cin>>n;
  
  cout<<"\nEnter The "<<n<<" Elemnts \n";
  
  for(i=0;i<n;i++)
  cin>>a[i];  
    
  int cand=majority(a,n);
    
  if(ismejority(a,n,cand))
      cout<<"Candidate key \n"<<cand;
    else
      cout<<"key is not found";
   return 0;
}

Output :-

C++ Program To Find Element That Appears More Than N/2 Times.

Extreme Recommended:- Like our Facebook Page or Join our Facebook Group and Google plus Community for up-to-date. If you have any Query or Question you can ask in the group, I will Try To Solve your Query and try to answers of your Questions withing 24 Hours, You can also Email me or comment below Please suggest to your Friends to join and like our page and don't forget to Subscribe. Enter your Email and click to subscribe.

subodh yadav

Ghanendra Yadav

Hello, I Am Ghanendra Yadav Owner of This Blog, I am professional Blogger and Programmer. I Love Programming, Logo Making, And Banner Designing. My Highest Qualification is MCA From NIT Warangal. You Can Find Me On Social Media Through Below Link And If You Have Any Query Related To Programming And Other Subject Comment Below or You Can Mail Me I Will Try To Answer Within 24 Hours Email:- yghanendra@student.nitw.ac.in

Find me on Social Media

Facebook | Twitter | Google+ | RSS Feed

No comments:

Post a Comment