Pagini recente » Cod sursa (job #2792625) | Cod sursa (job #2099818) | Cod sursa (job #1748218) | Cod sursa (job #358692) | Cod sursa (job #3032832)
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("algsort.in");
ofstream fout("algsort.out");
int N;
int Heap[500005], SIZE;
void Insert(int X, int POS)
{
Heap[POS] = X;
while(Heap[POS] < Heap[POS / 2] && POS / 2 >= 1)
{
swap(Heap[POS], Heap[POS / 2]);
POS = POS / 2;
}
}
void Delete_Radacina(int &SIZE)
{
swap(Heap[1], Heap[SIZE]);
SIZE --;
int POS_to_Go;
int i = 1;
while(true)
{
POS_to_Go = -1;
int left_i = 2 * i;
int right_i = 2 * i + 1;
if(left_i > SIZE)
break;
else
{
if(Heap[left_i] < Heap[i])
POS_to_Go = left_i;
}
if(right_i > SIZE);
else
{
if(Heap[right_i] < Heap[i] && Heap[right_i] < Heap[left_i])
POS_to_Go = right_i;
}
if(POS_to_Go == -1)
break;
else
{
swap(Heap[i], Heap[POS_to_Go]);
i = POS_to_Go;
}
}
}
void Read()
{
fin >> N;
for(int i = 1; i <= N; ++ i)
{
int X;
fin >> X;
Insert(X, i);
}
SIZE = N;
for(int i = 1; i <= N; ++ i)
{
fout << Heap[1] << " ";
Delete_Radacina(SIZE);
}
}
int main()
{
Read();
return 0;
}