Pagini recente » Cod sursa (job #824011) | Cod sursa (job #3159329) | Cod sursa (job #870697) | Cod sursa (job #588564) | Cod sursa (job #2424611)
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int parent(int i)
{
return i / 2;
}
int left_child(int i)
{
return 2 * i;
}
int right_child(int i)
{
return 2 * i + 1;
}
const int N = 500000 + 7;
int n, a[N], heap_dim;
void reconst(int i)
{
int l = left_child(i), r = right_child(i), poz = i;
if(l <= heap_dim && a[l] < a[poz])
poz = l;
if(r <= heap_dim && a[r] < a[poz])
poz = r;
if(i != poz)
{
swap(a[i], a[poz]);
reconst(poz);
}
}
void del()
{
swap(a[1], a[heap_dim]);
heap_dim--;
reconst(1);
}
void ins(int x)
{
heap_dim++;
a[heap_dim] = x;
int i = heap_dim;
while(i > 1 && a[parent(i)] > x)
{
swap(a[i], a[parent(i)]);
i = parent(i);
}
}
int main()
{
freopen("algsort.in", "r", stdin);
freopen("algsort.out", "w", stdout);
scanf("%d", &n);
for(int i = 1; i <= n; i++ )
{
int x;
scanf("%d", &x);
ins(x);
}
for(int i = 1; i <= n; i++)
{
printf("%d ", a[1]);
del();
}
printf("\n");
return 0;
}