#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cmath>
#include <cstdlib>


using namespace std;


void swap(int tree[], int a, int b)
{
    int temp;
    temp = tree[a];
    tree[a] = tree[b];
    tree[b] = temp;
}

void heapfy(int tree[], int n,int i) // 给第i个“堆”化
{
    if (i >= n)
    {
        return;
    }
    int c1 = 2 * i + 1;
    int c2 = 2 * i + 2;
    int min = i;
    if (c1 < n && tree[c1] < tree[min])
    {
        min = c1;
    }

    if (c2 < n && tree[c2] < tree[min])
    {
        min = c2;
    }

    if (i != min)
    {
        swap(tree, i, min);
        heapfy(tree, n, min);
    }
}


void build_tree(int tree[], int n)
{
    int num = n - 1;
    int parent = (n - 1) / 2;
    for (int i = parent; i >= 0; i--)
    {
        heapfy(tree, n, i);
    }
}




int main()
{
    int tree[1000];
    int n;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> tree[i];
    }

    build_tree(tree, n);

    for (int i = 0; i < n; i++)
    {
        cout << tree[i] << ' ';
    }

    return 0;
}
最后修改:2019 年 04 月 10 日
如果觉得我的文章对你有用,请随意赞赏