forked from hansrajdas/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmajority_element_in_array.c
79 lines (69 loc) · 1.68 KB
/
majority_element_in_array.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
* Date: 2018-09-27
*
* Description:
* Find majority element from an array, majority element in array is one that
* occurs more than n/2 times. It is guaranteed that array will surely have one
* such element which occurs more than n/2 times.
*
* Approach:
* - Assume first element as max occurring element, taking count = 1
* - Scan further in array, if same element appears, increment count by 1
* otherwise decrement count by 1
* - If count becomes 0, consider new element as max occurring element and
* reset count to 1
*
* This cancellation algorithm is called Moore's voting algorithm.
*
* Complexity:
* O(N)
*/
#include "stdio.h"
#include "stdlib.h"
int find_max_occuring_num (int arr[], int n) {
int i = 0;
int count = 1;
int maj_idx = 0;
for (i = 1; i < n; i++) {
if (arr[maj_idx] == arr[i])
count++;
else
count--;
if (!count) {
maj_idx = i;
count = 1;
}
}
return arr[maj_idx];
}
int main() {
int i = 0;
int n = 0, num_max_times = 0, ctr = 0;
int *a = NULL;
printf("Enter number of elements: ");
scanf("%d", &n);
a = (int *)malloc(sizeof(int) * n);
for (i = 0; i < n; i++) {
printf("Enter element[%d]: ", i);
scanf("%d", &a[i]);
}
num_max_times = find_max_occuring_num(a, n);
printf("Number occurring maximum times is: %d\n", num_max_times);
return 0;
}
/*
* Output:
* -----------------
* Enter number of elements: 10
* Enter element[0]: 4
* Enter element[1]: 4
* Enter element[2]: 2
* Enter element[3]: 3
* Enter element[4]: 6
* Enter element[5]: 6
* Enter element[6]: 4
* Enter element[7]: 4
* Enter element[8]: 4
* Enter element[9]: 15
* Number occurring maximum times is: 4
*/