-
Notifications
You must be signed in to change notification settings - Fork 0
/
nextmax1.c
73 lines (58 loc) · 1.13 KB
/
nextmax1.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
/* Calculate the max and the next max using the tournament data structure
*
* Created by: Pradyumna Shembekar
* Created on: 01/05/2016
**/
#include <stdio.h>
int main() {
int n, tourn[100];
/* Read number of inputs */
scanf("%d", &n);
printf("n = %d\n", n);
/* Build tournament */
buildtourn(tourn, n);
printf("MAX = %d\n", tourn[1]);
/* Calculate next maximum */
printf("NEXT MAX = %d\n", nextmax(tourn, n));
return 0;
}
int buildtourn(t, n)
int t[], n; {
int i;
/* Store input from n to 2n - 1*/
for (i = n; i <= 2*n - 1; i += 1) {
scanf("%d", &t[i]);
}
for (i = 2*n - 2; i > 1; i -= 2) {
t[i/2] = maxi(t[i], t[(i + 1)]);
}
for (i = 1; i <= 2*n - 1; i += 1) {
printf("%d ", t[i]);
}
return 0;
}
int nextmax(a, n)
int a[], n;
{
int i = 2, next;
next = min(a[i], a[(i + 1)]);
while (i < 2*n - 1) {
if (a[i] > a[(i + 1)]) {
if (next > a[(i + 1)]) next = a[(i + 1)];
i = 2*i;
}
else {
if (next < a[i]) next = a[i];
i = 2*(i + 1);
}
}
return next;
}
int maxi(int a, int b) {
if (a > b) return a;
else return b;
}
int min(int a, int b) {
if (a < b) return a;
else return b;
}