-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtop_n.c
158 lines (136 loc) · 2.65 KB
/
top_n.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
int g_heapsize;
int heap_left(int parent)
{
int left = 0;
if(parent <= g_heapsize/2)
{
left = parent*2;
}
return left;
}
int heap_right(int parent)
{
int right = 0;
if(parent <= g_heapsize/2)
{
right = parent*2 + 1;
if(right>g_heapsize)
{
right = 0;
}
}
return right;
}
void heap_exchange(int array[], int i, int j)
{
int tmp;
assert(NULL != array);
tmp = array[i];
array[i] = array[j];
array[j] = tmp;
return;
}
void heap_min_ify(int array[], int index)
{
int left, right, lowest;
assert(NULL != array);
if((index > g_heapsize/2) || (index==0))
{
return;
}
left = heap_left(index);
right = heap_right(index);
lowest = index;
if((array[lowest] > array[left]) && (left != 0))
{
lowest = left;
}
if((array[lowest] > array[right]) && (right != 0))
{
lowest = right;
}
if(lowest != index)
{
heap_exchange(array, index, lowest);
heap_min_ify(array, lowest);
}
return;
}
void heap_build(int array[])
{
int index;
assert(NULL != array);
for(index=g_heapsize/2; index>0; index--)
{
heap_min_ify(array, index);
}
return;
}
void find_top(int array[], FILE *fp)
{
int next, index, tmp;
char buf[256], *ptr;
assert(NULL != array);
assert(NULL != fp);
index = 1;
while((index<=g_heapsize) && (NULL != (ptr=fgets(buf, sizeof(buf), fp))))
{
array[index] = atoi(buf);
index++;
}
if(NULL == ptr)
{
while(index<=g_heapsize)
{
array[index] = 0;
index++;
}
}
heap_build(array);
while(NULL != fgets(buf, sizeof(buf), fp))
{
tmp = atoi(buf);
if(tmp > array[1])
{
array[1] = tmp;
heap_min_ify(array, 1);
}
}
return;
}
int main(int argc, char *argv[])
{
int index, size;
FILE *in, *out;
int *array;
char buf[20];
assert(4 == argc);
in = fopen(argv[1], "r");
out = fopen(argv[2], "w");
if((NULL == in) || (NULL == out))
{
return -1;
}
g_heapsize = atoi(argv[3]);
size = sizeof(int)*(g_heapsize+1);
array = malloc(size);
if(NULL == array)
{
return -1;
}
memset(array, 0, size);
find_top(array, in);
for(index=1; index<=g_heapsize; index++)
{
snprintf(buf, sizeof(buf), "%d", array[index]);
fputs(buf, out);
fputs("\n", out);
}
fclose(in);
fclose(out);
free(array);
}