Pagini recente » Cod sursa (job #2565269) | Cod sursa (job #2208591) | Cod sursa (job #1247697) | Cod sursa (job #455899) | Cod sursa (job #2669645)
#include <fstream>
using namespace std;
ifstream fin("algsort.in");
ofstream fout("algsort.out");
const int NMax = 500000;
int N,NHeap;
int X[NMax + 5],Heap[NMax + 5];
void Read()
{
fin >> N;
for(int i = 1; i <= N; ++i)
fin >> X[i];
}
void UpHeap(int Nod)
{
int Father = Nod / 2;
if(Father && Heap[Father] > Heap[Nod])
{
swap(Heap[Father],Heap[Nod]);
UpHeap(Father);
}
}
void DownHeap(int Nod)
{
int Son1 = 2 * Nod,Son2 = 2 * Nod + 1;
if(Son1 > NHeap)
return;
if(Son1 == NHeap)
{
if(Heap[Son1] < Heap[Nod])
{
swap(Heap[Son1],Heap[Nod]);
return;
}
}
if(Heap[Son1] < Heap[Son2])
{
if(Heap[Son1] < Heap[Nod])
{
swap(Heap[Son1],Heap[Nod]);
DownHeap(Son1);
}
}
else
{
if(Heap[Son2] < Heap[Nod])
{
swap(Heap[Son2],Heap[Nod]);
DownHeap(Son2);
}
}
}
void BuildHeap()
{
for(int i = 1; i <= N; ++i)
{
Heap[++NHeap] = X[i];
UpHeap(NHeap);
}
}
void HeapSort()
{
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] << " ";
fout << "\n";
}
int main()
{
Read();
BuildHeap();
HeapSort();
Print();
return 0;
}