forked from ajeetshah/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray-p2-maj-el.c
More file actions
84 lines (72 loc) · 1.34 KB
/
array-p2-maj-el.c
File metadata and controls
84 lines (72 loc) · 1.34 KB
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
80
81
82
83
84
#include<stdio.h>
#define N 10
/* the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. ... You generally use this syntax when creating constants that represent numbers, strings or expressions. */
void swap(int A[], int i, int j) {
int t;
t = A[i];
A[i] = A[j];
A[j] = t;
}
// we are shorthing an array either in assending or in descendig order//
void sortArray(int A[], int n) {
int i, j;
int min;
for (i=0; i<n-1; i++) {
min = i;
for (j=i+1; j<n; j++) {
if (A[min] > A[j]) {
min = j;
}
}
if (i!=min) {
swap(A, i, min);
}
}
}
/* the function which we have made above we can use that here */
int findMajority(int A[], int n, int *major) {
int found = 0;
int i;
int c = 1;
for (i=0; i<n-1; i++) {
if (A[i] == A[i+1]) {
c++;
if (c > n/2) {
*major = A[i];
found = 1;
return found;
}
}
else {
c = 1;
}
}
return found;
}
int main() {
int i;
int A[N] = {
9, 3, 9, 4, 9,
9, 5, 9, 9, 12
};
sortArray(A, N);
for (i=0; i<N; i++) {
printf("%d ", A[i]);
}
printf("\n");
int major;
int found = findMajority(A, N, &major);
if (found) {
printf("majority: %d\n", major);
}
else {
printf("NONE");
}
return 0;
}
/*
*
* 1. O(sort) + n-1 comparisions
* 2.
*
*/