-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathquestion9.c
58 lines (47 loc) · 1.27 KB
/
question9.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
Given an array A of size n, find an element that occurs more than n/2 times
MOORE VOTING ALGORITHM
In this algo every element votes for itself. If a different element in encountered then the vote collected
for previous element is used to cancel out the vote for this element.
When votes is zero and new element is found voter changes
The number of votes have to be greater than or equal to 1 to satisfy the condition given in the problem
always
If it is greater than or equal to one, we loop the array again to find how many times is the voter occuring.
Time complexity:
O(n)
Space complexity:
O(1)
*/
#include <stdio.h>
#include <stdlib.h>
int main(){
int index,voter, votes=0, counter=0;
int a[] = {2,2,5,6,2,2};
int length = sizeof(a)/sizeof(a[0]);
//checking voter and votes
for(index = 0; index<length; index++){
if(votes == 0){
voter = a[index];
votes++;
}else{
if(voter == a[index]){
votes++;
}else{
votes--;
}
}
}
//checking if that element is really repeating more than n/2 times or not
if(votes >= 1){
for(index=0; index<length; index++){
if(a[index]==voter){
counter++;
}
}
if(counter > length/2){
printf("the element that occurs more than n/2 times is %d\n", voter);
}else{
printf("no element found\n");
}
}
}