堆排序
ycx303
·
·
个人记录
#include <iostream>
#include <cmath>
using namespace std;
int a[100005];
void heapinsert(int pos)
{
int t = (pos - 1) / 2;
while (pos > 0 && a[pos] > a[t])
{
swap(a[pos], a[t]);
pos = t;
t = (pos - 1) / 2;
}
}
void heapify(int pos, int r)
{
int t = pos * 2 + 1;
while (t < r)
{
int best = (t + 1 < r && a[t + 1] > a[t]) ? t + 1 : t;
best = a[best] > a[pos] ? best : pos;
if (best == pos) break;
swap(a[best], a[pos]);
pos = best;
t = pos * 2 + 1;
}
}
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i ++)
{
cin >> a[i];
heapinsert(i);
}
int p = n;
while (p > 1)
{
swap(a[0], a[p - 1]);
p --;
heapify(0, p);
}
for (int i = 0; i < n; i ++)
{
cout << a[i] << " ";
}
cout << endl;
return 0;
}