Pagini recente » Cod sursa (job #599599) | Cod sursa (job #3188984) | Cod sursa (job #971319) | Cod sursa (job #183435) | Cod sursa (job #2286460)
#include <iostream>
#include <fstream>
using namespace std;
ifstream in("algsort.in");
ofstream out("algsort.out");
const int NMax = 1e5;
int N, NHeap, X[NMax], Heap[NMax];
void Read(){
in >> N;
for (int i = 1; i <= N; ++i)
in >> X[i];
}
void DownHeap(int Nod){
int Son1 = Nod * 2;
int Son2 = Nod * 2 + 1;
if (Son1 > NHeap)
return;
if (Son1 == NHeap){
if (Heap[Nod] > Heap[Son1])
swap(Heap[Nod], Heap[Son1]);
return;
}
if (Heap[Son1] < Heap[Son2]){
if (Heap[Nod] > Heap[Son1]){
swap(Heap[Nod], Heap[Son1]);
DownHeap(Son1);
}
}
else
if (Heap[Nod] > Heap[Son2]){
swap(Heap[Nod], Heap[Son2]);
DownHeap(Son2);
}
}
void UpHeap(int Nod){
int Father = Nod / 2;
if (Heap[Nod] < Heap[Father] && Father){
swap(Heap[Nod], Heap[Father]);
UpHeap(Father);
}
}
void BuildHeap(){
for (int i = 1; i <= N; ++i){
Heap[i] = X[i];
UpHeap(i);
}
NHeap = N;
}
void HeapSort(){
while (NHeap){
out << Heap[1] << " ";
Heap[1] = Heap[NHeap--];
DownHeap(1);
}
out << '\n';
}
int main(){
Read();
BuildHeap();
HeapSort();
return 0;
}