-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap sort 연습.cpp
68 lines (59 loc) · 979 Bytes
/
heap sort 연습.cpp
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
#include <stdio.h>
int heap[100000];
int n;
int hsize = 0;
void insert_heap(int value)
{
//¸Ç ¸¶Áö¸·¿¡ ³Ö ±â
heap[++hsize] = value;
int x = hsize;
while (x > 1) {
if (heap[x] < heap[x / 2]) {
int t = heap[x];
heap[x] = heap[x / 2];
heap[x / 2] = t;
x = x / 2;
}
else {
break;
}
}
}
int pop_heap()
{
int pop = heap[1];
heap[1] = heap[hsize--];
int x = 1;
while (x*2 <= hsize) {
int small_child;
if (heap[x * 2] < heap[x * 2 + 1] || x*2+1 > hsize) {
small_child = x * 2;
}
else {
small_child = x * 2 + 1;
}
if (heap[x] > heap[small_child]) {
int t = heap[x];
heap[x] = heap[small_child];
heap[small_child] = t;
x = small_child;
}
else
{
break;
}
}
return pop;
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++) {
int t;
scanf("%d", &t);
insert_heap(t);
}
while (hsize > 0) {
printf("%d ", pop_heap());
}
}