Pagini recente » Cod sursa (job #888833) | Cod sursa (job #914110) | Cod sursa (job #1696036) | Cod sursa (job #2174696) | Cod sursa (job #880146)
Cod sursa(job #880146)
// Include
#include <fstream>
#include <algorithm>
using namespace std;
// Definitii
#define father node/2
#define leftSon node*2
#define rightSon node*2 + 1
// Constante
const int sz = (int)5e5+1;
// Functii
bool checkDown(int node);
// Variabile
ifstream in("algsort.in");
ofstream out("algsort.out");
int heapSize, num;
int heap[sz];
// Main
int main()
{
in >> num;
heapSize = num;
for(int i=1 ; i<=num ; ++i)
in >> heap[i];
for(int i=1 ; i<=heapSize ; ++i)
checkDown(i);
while(heapSize != 1)
{
swap(heap[1], heap[heapSize--]);
for(int i=1 ; i<=heapSize ; ++i)
checkDown(i);
}
for(int i=1 ; i<=num ; ++i)
out << heap[i] << ' ';
in.close();
out.close();
return 0;
}
bool checkDown(int node)
{
if(!node || node > heapSize)
return false;
if(rightSon <= heapSize) // are 2 fii
{
if(heap[node] < heap[leftSon] && heap[node] < heap[rightSon]) // ambii lui fii sunt mai mari ca el
{
if(heap[leftSon] < heap[rightSon]) // cel din dreapta e mai mare
swap(heap[node], heap[rightSon]);
else
swap(heap[node], heap[leftSon]);
if(checkDown(father))
checkDown(node);
return true;
}
if(heap[node] < heap[leftSon]) // doar fiul stang e mai mare
{
swap(heap[node], heap[leftSon]);
if(checkDown(father))
checkDown(node);
return true;
}
if(heap[node] < heap[rightSon]) // doar fiul drept e mai mare
{
swap(heap[node], heap[rightSon]);
if(checkDown(father))
checkDown(node);
return true;
}
return false;
}
if(leftSon == heapSize) // are un singur fiu
{
if(heap[node] < heap[leftSon]) // fiul lui e mai mare
{
swap(heap[node], heap[leftSon]);
if(checkDown(father))
checkDown(node);
return true;
}
return false;
}
return false;
}