#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<math.h>
#include<set>
using namespace std;
int tree[1000];
void heapify(int n, int i)
{
int c1 = 2 * i + 1;
int c2 = 2 * i + 2;
int max = i;
if (c1<n && tree[c1]>tree[max])
{
max = c1;
}
if (c2<n && tree[c2]>tree[max])
{
max = c2;
}
if (max != i)
{
int temp = tree[i];
tree[i] = tree[max];
tree[max] = temp;
heapify(n, max);
}
}
void build_heap(int n)
{
int last_node = n - 1;
int parent = (last_node - 1) / 2;
for (int i = parent; i >= 0; i--)
{
heapify(n, i);
}
}
void heap_sort(int n)
{
build_heap(n);
for (int i = n - 1; i >= 0; i--)
{
int temp = tree[i];
tree[i] = tree[0];
tree[0] = temp;
heapify(i, 0);
}
}
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
scanf("%d", &tree[i]);
}
heap_sort(n);
for (int i = 0; i < n; i++)
{
printf("%d ", tree[i]);
}
return 0;
}
堆排序
最新推荐文章于 2022-06-06 15:02:30 发布