Pagini recente » Cod sursa (job #1923477) | Cod sursa (job #1096953) | Cod sursa (job #2941799) | Cod sursa (job #1647723) | Cod sursa (job #1465404)
#include <fstream>
#include <algorithm>
#define NMAX 1000005
using namespace std;
ifstream f("algsort.in");
ofstream g("algsort.out");
int heap[NMAX], i, n, m = 0, nr;
int father(int x)
{
return x/2;
}
int left_son(int x)
{
return 2*x;
}
int right_son(int x)
{
return 2*x + 1;
}
void go_up(int k)
{
while (heap[k] < heap[father(k)] && k > 1)
{
swap(heap[k], heap[father(k)]);
k = father(k);
}
}
void go_down(int k)
{
int aux = 0;
do
{
aux = 0;
if (left_son(k) <= m)
aux = left_son(k);
if (right_son(k) <= m && heap[right_son(k)] < heap[aux])
aux = right_son(k);
if (heap[left_son(k)] > heap[k] && heap[right_son(k)] > heap[k])
aux = 0;
if (aux != 0)
{
swap(heap[aux], heap[k]);
k = aux;
}
}while (aux);
}
void insert_heap(int x)
{
heap[++m] = x;
go_up(m);
go_down(1);
}
void delete_heap(int k)
{
heap[k] = heap[m];
m --;
go_down(k);
}
int main()
{
f >> n;
for (i=1; i<=n; ++i)
{
f >> nr;
insert_heap(nr);
}
while (m)
{
g << heap[1] << " ";
delete_heap(1);
}
return 0;
}