-
Notifications
You must be signed in to change notification settings - Fork 438
/
Heap-Sort.cpp
65 lines (55 loc) · 848 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
#include <cstdio>
#include <cstdlib>
#define MAX_HEAP_SIZE 100000
using namespace std;
int n, H[MAX_HEAP_SIZE], heapsize;
void min_heapify(int i)
{
int smallest = i;
int lch = i << 1;
int rch = lch + 1;
if (lch <= heapsize && H[smallest] > H[lch])
{
smallest = lch;
}
if (rch <= heapsize && H[smallest] > H[rch])
{
smallest = rch;
}
if (smallest != i)
{
int temp = H[smallest];
H[smallest] = H[i];
H[i] = temp;
min_heapify(smallest);
}
}
void build_heap()
{
for (int i = heapsize >> 1; i >= 1; i--)
{
min_heapify(i);
}
}
int extract_min()
{
int res = H[1];
H[1] = H[heapsize--];
min_heapify(1);
return res;
}
int main()
{
scanf("%d", &n);
heapsize = n;
for (int i = 1; i <= n; i++)
{
scanf("%d", &H[i]);
}
build_heap();
while (heapsize > 0)
{
printf("%d\n", extract_min());
}
return 0;
}