Skip to content

Commit e939b0c

Browse files
authored
堆排序
1 parent 5557ef5 commit e939b0c

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

Heap-Sort.cpp

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
#include <cstdio>
2+
#include <cstdlib>
3+
4+
#define MAX_HEAP_SIZE 100000
5+
6+
using namespace std;
7+
8+
int n, H[MAX_HEAP_SIZE], heapsize;
9+
10+
void min_heapify(int i)
11+
{
12+
int smallest = i;
13+
int lch = i << 1;
14+
int rch = lch + 1;
15+
16+
if (lch <= heapsize && H[smallest] > H[lch])
17+
{
18+
smallest = lch;
19+
}
20+
if (rch <= heapsize && H[smallest] > H[rch])
21+
{
22+
smallest = rch;
23+
}
24+
25+
if (smallest != i)
26+
{
27+
int temp = H[smallest];
28+
H[smallest] = H[i];
29+
H[i] = temp;
30+
min_heapify(smallest);
31+
}
32+
}
33+
34+
void build_heap()
35+
{
36+
for (int i = heapsize >> 1; i >= 1; i--)
37+
{
38+
min_heapify(i);
39+
}
40+
}
41+
42+
int extract_min()
43+
{
44+
int res = H[1];
45+
H[1] = H[heapsize--];
46+
min_heapify(1);
47+
return res;
48+
}
49+
50+
int main()
51+
{
52+
scanf("%d", &n);
53+
heapsize = n;
54+
for (int i = 1; i <= n; i++)
55+
{
56+
scanf("%d", &H[i]);
57+
}
58+
build_heap();
59+
while (heapsize > 0)
60+
{
61+
printf("%d\n", extract_min());
62+
}
63+
64+
return 0;
65+
}

0 commit comments

Comments
 (0)