堆排序模版

 1 #include <iostream>
 2 #include <cmath>
 3 using namespace std;
 4 
 5 int a[1020];
 6 
 7 void fix(int a[], int i, int n)
 8 {
 9     int l = 2 * i, r = 2 * i + 1, maxx = i;
10     if (l <= n && a[l] > a[i])
11     {
12         maxx = l;
13     }
14     else{
15         maxx = i;
16     }
17     if (r <= n && a[r] > a[maxx])
18     {
19         maxx = r;
20     }
21     if (maxx != i)
22     {
23         swap(a[i], a[maxx]);
24         fix(a, maxx, n);
25     }
26 }
27 void heap_sort(int a[], int n)
28 {
29     for (int i = n / 2 - 1; i >= 0; i--)
30     {
31         fix(a, i, n - 1);
32     }
33     for (int i = n - 1; i >= 1; i--)
34     {
35         swap(a[0], a[i]);
36         fix(a, 0, i - 1);
37     }
38 }
39 int main()
40 {
41     int n, m;
42     while (cin >> n)
43     {
44         if (n == 0)break;
45         cin >> m;
46         for (int i = 0; i < n; i++)
47         {
48             cin >> a[i];
49         }
50         heap_sort(a, n);
51         if (m == 0)
52         {
53             for (int i = 0; i < n - 1; i++)
54             {
55                 cout << a[i] << " ";
56             }
57             cout << a[n - 1] << endl;
58         }
59         else{
60             for (int i = n - 1; i > 0; i--)
61             {
62                 cout << a[i] << " ";
63             }
64             cout << a[0] << endl;
65         }
66     }
67     
68 
69     return 0;
70 }

 

posted @ 2021-06-22 11:04  TTTCoder  阅读(99)  评论(0编辑  收藏  举报