Pagini recente » Cod sursa (job #2756672) | Cod sursa (job #2609938) | Cod sursa (job #2419714) | Cod sursa (job #2460743) | Cod sursa (job #1575668)
#include <fstream>
using namespace std;
ifstream fin("algsort.in");
ofstream fout("algsort.out");
const int NMax = 500005;
int X[NMax],Heap[NMax];
int N,NHeap;
void Read()
{
fin>>N;
for(int i = 1; i<=N; i++)
fin>>X[i];
}
void Upheap(int Nod)
{
int Tata = Nod / 2;
if(Tata && Heap[Tata]>Heap[Nod])
{
swap(Heap[Nod],Heap[Tata]);
Upheap(Tata);
}
}
void BuildHeap()
{
for(int i = 1; i<=N; i++)
{
Heap[++NHeap] = X[i];
Upheap(NHeap);
}
}
void DownHeap(int Nod)
{
int Son = 2*Nod;
if(Son > NHeap)
return;
if(Son == NHeap && Heap[Son] < Heap[Nod])
{
swap(Heap[Son],Heap[Nod]);
return;
}
if(Heap[Son] < Heap[Son+1])
{
if(Heap[Son] < Heap[Nod])
{
swap(Heap[Son], Heap[Nod]);
DownHeap(Son);
}
}
else
{
if(Heap[Son+1] < Heap[Nod])
{
swap(Heap[Son+1], Heap[Nod]);
DownHeap(Son+1);
}
}
}
void Sort()
{
BuildHeap();
for(int i = 1; i<=N; i++)
{
X[i] = Heap[1];
Heap[1] = Heap[NHeap--];
DownHeap(1);
}
}
void Print()
{
for(int i = 1; i<=N; i++)
fout<<X[i]<<" ";
}
int main()
{
Read();
Sort();
Print();
return 0;
}