Pagini recente » Cod sursa (job #140855) | Cod sursa (job #264231) | Cod sursa (job #1410626) | Cod sursa (job #917929) | Cod sursa (job #1090287)
// Include
#include <fstream>
using namespace std;
// Definitii
#define father (node>>1)
#define leftSon (node<<1)
#define rightSon (node<<1)+1
// Constante
const int sz = (int)5e5+1;
const int root = 1;
// Functii
void checkUp(int node);
void checkDown(int node);
// Variabile
ifstream in("algsort.in");
ofstream out("algsort.out");
int num, heapSize;
int heap[sz];
// Main
int main()
{
in >> num;
while(++heapSize <= num)
{
in >> heap[heapSize];
checkUp(heapSize);
}
--heapSize;
while(heapSize != 1)
{
swap(heap[root], heap[heapSize--]);
checkDown(root);
}
for(int i=1 ; i<=num ; ++i)
out << heap[i] << ' ';
out << '\n';
in.close();
out.close();
return 0;
}
void checkUp(int node)
{
if(node == root)
return;
if(heap[father] < heap[node])
{
swap(heap[node], heap[father]);
checkUp(father);
}
return;
}
void checkDown(int node)
{
if(heapSize < node)
return;
if(rightSon <= heapSize)
{
if(heap[node] < heap[leftSon] && heap[node] < heap[rightSon])
{
if(heap[leftSon] <= heap[rightSon])
{
swap(heap[node], heap[rightSon]);
checkDown(rightSon);
}
else
{
swap(heap[node], heap[leftSon]);
checkDown(leftSon);
}
return;
}
if(heap[node] < heap[leftSon])
{
swap(heap[node], heap[leftSon]);
checkDown(leftSon);
}
if(heap[node] < heap[rightSon])
{
swap(heap[node], heap[rightSon]);
checkDown(rightSon);
}
return;
}
if(leftSon == heapSize)
{
if(heap[node] < heap[leftSon])
{
swap(heap[node], heap[leftSon]);
checkDown(leftSon);
}
return;
}
}