Pagini recente » Cod sursa (job #2350637) | Cod sursa (job #841035) | Cod sursa (job #906587) | Cod sursa (job #1986997) | Cod sursa (job #1007678)
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
ifstream f("algsort.in");
ofstream g("algsort.out");
int n,h[500005];
void sift(int k)
{ int ok=1,son;
while(ok)
{ son=2*k; if (son>n) break;
if (son<n && h[2*k+1]<h[son]) son=2*k+1;
if (h[son]<h[k]) {swap(h[son],h[k]); k=son;}
else ok=0;
}
}
void percolate(int k)
{
while(h[k]<h[k/2] && k>1)
{swap(h[k],h[k/2]);
k/=2;
}
}
void insert(int nr)
{ n++; h[n]=nr;
percolate(n);
}
void cut(int k)
{ h[k]=h[n]; n--;
if (h[k]<h[k/2] && k>1) percolate(k);
else sift(k);
}
void MakeHeap()
{ int i;
for(i=n/2;i>=1;i--) sift(i);
}
void SortHeap()
{ int i,el=n;
for(i=1;i<=el;i++)
{ g<<h[1]<<" ";
cut(1);
}
}
int main()
{ int i;
f>>n;
for(i=1;i<=n;i++)
f>>h[i];
MakeHeap();
SortHeap();
return 0;
}