Pagini recente » Cod sursa (job #1986402) | Cod sursa (job #2284101) | Cod sursa (job #1476319) | Cod sursa (job #2888654) | Cod sursa (job #360236)
Cod sursa(job #360236)
#include<fstream.h>
int n,i,h[500010];
void swap(int i, int j)
{
int aux;
aux=h[i]; h[i]=h[j]; h[j]=aux;
}
void update(int poz)
{
int aux;
while(poz/2 >=1 && h[poz]>h[poz/2] )
{
aux=h[poz]; h[poz]=h[poz/2]; h[poz/2]=aux;
poz/=2;
}
}
void update2(int n)
{
int poz=1,cont=1;
while(2*poz<=n && cont)
{
cont=0;
if(2*poz+1<=n)
{ if(h[poz]<h[2*poz])
if(h[poz]<h[2*poz+1])
if(h[2*poz]<h[2*poz+1])
{swap(poz,2*poz+1); poz=2*poz+1;
cont=1;
}
else {swap(poz,2*poz); cont=1; poz*=2; }
else {swap(poz,2*poz); cont=1; poz*=2;}
}
else
if(h[poz]<h[2*poz])
{swap(poz,2*poz);cont=1; poz*=2;}
}
}
int main()
{
ifstream f("algsort.in");
ofstream g("algsort.out");
f>>n;
for(i=1;i<=n;i++)
{ f>>h[i];
update(i);
}
for(i=n;i>1;i--)
{ swap(1,i);
update2(i-1);
}
for(i=1;i<=n;i++) g<<h[i]<<" ";
return 0;
}