Pagini recente » Cod sursa (job #3233961) | Cod sursa (job #1045017) | preONI 2008 - Clasament Runda 4, Clasele 5-8 | Cod sursa (job #545389) | Cod sursa (job #2705763)
#include <fstream>
using namespace std;
ifstream fin("algsort.in");
ofstream fout("algsort.out");
const int NMax = 500000;
int X[NMax + 5],Heap[NMax + 5];
int N, NHeap;
void Read()
{
fin >> N;
for(int i = 1; i <= N ; ++i)
fin >> X[i];
}
void UpHeap(int Pos)
{
int Father = Pos / 2;
if( Father != 0 && Heap[Father] > Heap[Pos])
{
swap(Heap[Father],Heap[Pos]);
UpHeap(Father);
}
}
void BuildHeap()
{
for(int i = 1; i <= N; ++i)
{
Heap[++NHeap] = X[i];
UpHeap(NHeap);
}
}
void DownHeap(int Pos)
{
int Son,Son1 = 2 * Pos, Son2 = 2 * Pos + 1;
if(Son1 > NHeap)
return;
if(Son1 == NHeap)
{
if(Heap[Son1] < Heap[Pos])
swap(Heap[Son1],Heap[Pos]);
return;
}
if(Heap[Son1] < Heap[Son2])
Son = Son1;
else
Son = Son2;
if(Heap[Son] < Heap[Pos])
{
swap(Heap[Son],Heap[Pos]);
DownHeap(Son);
}
}
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();
}