Pagini recente » Cod sursa (job #2980421) | Cod sursa (job #2345637) | Cod sursa (job #3283255) | Cod sursa (job #480302) | Cod sursa (job #1298597)
#include <fstream>
#include <cstring>
using namespace std;
ifstream f("algsort.in");
ofstream g("algsort.out");
const int NMAX=500001;
class Heap
{
private:
int size, h[NMAX], ph[NMAX],val[NMAX];
void percolate(int nod)
{
while(nod/2 && val[h[nod/2]]>val[h[nod]])
{
swap(h[nod],h[nod/2]);
ph[h[nod]]=nod;
ph[h[nod/2]]=nod/2;
nod=nod/2;
}
}
void sift(int nod)
{
int f1,f2,son=nod;
do
{
nod=son;
f1=2*nod;
f2=2*nod+1;
if(f2<=size && val[h[f2]]<val[h[son]]) son=f2;
if(f1<=size && val[h[f1]]<val[h[son]]) son=f1;
swap(h[son],h[nod]);
ph[h[son]]=son;
ph[h[nod]]=nod;
}while(nod!=son);
}
public:
Heap()
{
size=0;
memset(h,0,sizeof(h));
memset(ph,0,sizeof(ph));
}
int heapSize()
{
return size;
}
void addHeap(int x)
{
val[++size]=x;
h[size]=size;
ph[size]=size;
percolate(size);
}
int pop_front()
{
int aux=h[1];
h[1]=h[size];
ph[h[1]]=1;
sift(1);
size--;
return val[aux];
}
}heap;
int main()
{
int N;
f>>N;
int i,x;
for(i=1;i<=N;i++)
{
f>>x;
heap.addHeap(x);
}
while(heap.heapSize()>0)
{
x=heap.pop_front();
g<<x<<' ';
}
}