Pagini recente » Cod sursa (job #380862) | Cod sursa (job #1588378) | Cod sursa (job #2558907) | Cod sursa (job #2935034) | Cod sursa (job #1052825)
#include <fstream>
#define nmax 500001
using namespace std;
ifstream f("algsort.in");
ofstream g("algsort.out");
int h[nmax],ph[nmax],v[nmax],n,sh;
void swap(int x, int y)
{
int aux;
aux=h[x];
h[x]=h[y];
h[y]=aux;
}
void perco(int p)
{
while(v[h[p]]<v[h[p/2]] && p/2)
{
swap(p,p/2);
ph[h[p/2]]=p/2;
ph[h[p]]=p;
p=p/2;
}
}
void sift(int p)
{
int f1=2*p,f2=2*p+1,pn;
if(f1>sh) return;
if(f2>sh) f2=f1;
if(v[h[f1]]<v[h[f2]]) pn=f1;
else pn=f2;
if(v[h[p]]<=v[h[pn]]) return;
else
{
swap(p,pn);
ph[h[p]]=p;
ph[h[pn]]=pn;
sift(pn);
}
}
int main()
{
f>>n;
int i,x;
for(i=1;i<=n;i++)
{
f>>v[i];
h[++sh]=i;
ph[i]=sh;
perco(sh);
}
while(sh)
{
g<<v[h[1]]<<' ';
h[1]=h[sh]; sh--;
ph[h[1]]=1;
sift(1);
}
}