Pagini recente » Cod sursa (job #939221) | Cod sursa (job #1499455) | Cod sursa (job #1986681) | Cod sursa (job #1650104) | Cod sursa (job #2929282)
#include <bits/stdc++.h>
using namespace std;
const int NMax = 100000;
int Heap[NMax + 5],X[NMax + 5];
int NHeap,N;
void UpHeap(int Nod)
{
int Tata = Nod / 2;
if(Tata && Heap[Tata] > Heap[Nod])
{
swap(Heap[Tata],Heap[Nod]);
UpHeap(Tata);
}
}
void DownHeap(int Nod)
{
int Son1, Son2, Son;
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])
{
Son = Son1;
}
else
{
Son = Son2;
}
if(Heap[Son] < Heap[Nod])
{
swap(Heap[Son],Heap[Nod]);
DownHeap(Son);
}
}
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 Read()
{
cin >> N;
for(int i = 1; i <= N; ++i)
cin >> X[i];
}
void Print()
{
for(int i = 1; i <= N; ++i)
cout << X[i] << " ";
}
int main()
{
freopen("taxa.in" , "r" , stdin);
freopen("taxa.out" , "w" ,stdout);
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
Read();
BuildHeap();
HeapSort();
Print();
}