Election Winner
Algorithm
Input Number of voter .leader id
Output Winner of the election.
complexity O(n).
Election()
1. Set n=Input number of candidates participating in election.
2. Set b[X] //input vote from X number of voters where X is unknown
3. for j=1 to n.
4. do Initialize candidate array a[j] = 0
5. for j = 1 to X.
6. do Increment a[b[j]]++
7. Set max := a[1];
8. Repeat for j = 1 to n
If (max< a[j])
then set max := j.
9. Return max.
10. End
Algorithm Description
C Code
/* program to find a winner in an election where votes are stored in an array*/
#include<stdio.h>
#include<conio.h>
int *quick(int p,int r);
int partition(int p,int r);
int votes[100],n;
int main()
{
int *p=0,i;
int max=0,winner=1;
int count=1;
printf("enter no. of voters\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter vote no. %d to a candidate\n",i+1);
scanf("%d",&votes[i]);
}
p=quick(0,n-1); //sorts array
printf("sorted array is \n");
for(i=0;i<n;i++)
printf("%d\n",*(i+p));
for(i=0;i<n;i++)
{
if(votes[i]==votes[i+1]) //if two consecutive votes are for same candidate
{
count++;
continue;
}
else
{
if(count>max) //no. of votes greater than last greater votes' candidate
{
max=count;
winner=votes[i];
}
count=0;
}
}
printf("winner is candidate %d\n",winner);
return 0;
}
int *quick(int p,int r)
{
int q=0;
if(p<r)
{
q=partition(p,r); //partitioning the array
quick(p,q-1);
quick(q+1,r);
}
return votes;
}
int partition(int p,int r)
{
int x=votes[r];
int i=p-1;
int j,temp;
for(j=p;j<r;j++)
{
if(votes[j]<=x)
{
i++;
temp=votes[i];
votes[i]=votes[j];
votes[j]=temp;
}
}
temp=votes[i+1];
votes[i+1]=votes[r];
votes[r]=temp;
return (i+1);
}