Pagini recente » Cod sursa (job #197886) | Cod sursa (job #584278) | Cod sursa (job #731311) | Cod sursa (job #1322859) | Cod sursa (job #1545738)
#include <fstream>
#include <algorithm>
using namespace std;
ifstream fin("algsort.in");
ofstream fout("algsort.out");
int N, M;
int V[500005], H[500005];
int left_son(int x)
{
return 2 * x;
}
int right_son(int x)
{
return 2 * x + 1;
}
int father(int x)
{
return x / 2;
}
void percolate(int nod) // urca
{
while ((nod > 1) && H[nod] > H[father(nod)])
{
swap(H[nod], H[father(nod)]);
nod = father(nod);
}
}
void sift(int nod) // coboara
{
int son = 1;
while (son)
{
son = 0;
if (left_son(nod) <= M)
{
son = left_son(nod);
if (right_son(nod) <= M && H[right_son(nod)] > H[left_son(nod)])
son = right_son(nod);
if (H[son] <= H[nod])
son = 0;
}
if (son)
{
swap(H[nod], H[son]);
nod = son;
}
}
}
void cut(int nod)
{
if (nod == 0)
return;
swap(H[nod], H[M]);
--M;
if ((nod > 1) && H[nod] > H[father(nod)])
percolate(nod);
else
sift(nod);
}
int main()
{
fin >> N;
for (int i = 1, x; i <= N; ++i)
{
fin >> x;
H[++M] = x;
percolate(M);
}
while (M)
{
V[M] = H[1];
cut(1);
}
for (int i = 1; i <= N; ++i)
fout << V[i] << ' ';
fin.close();
fout.close();
return 0;
}