Pagini recente » Cod sursa (job #1662341) | Cod sursa (job #812178) | Cod sursa (job #950176) | Cod sursa (job #2048600) | Cod sursa (job #1735221)
#include <cstdio>
#include<ctype.h>
#define BUF_SIZE 4096
#define MAXN 500000
int n, heap[MAXN+1], pos=BUF_SIZE;
char buf[BUF_SIZE];
inline char getChar(FILE *f)
{
if(pos==BUF_SIZE) pos=0, fread(buf, 1, BUF_SIZE, f);
return buf[pos++];
}
inline int getInt(FILE *f)
{
char c;
int nr=0;
c=getChar(f);
while(!isdigit(c)) c=getChar(f);
while(isdigit(c)) nr=nr*10+c-'0', c=getChar(f);
return nr;
}
/* HEAAAAP SORTTTTT*/
inline int son_left(int x){ return x*2;}
inline int son_right(int x){ return x*2+1;}
inline int father(int x){ return x/2;}
inline void swap1(int p, int q)
{
int aux=heap[p];
heap[p]=heap[q];
heap[q]=aux;
}
inline void down(int x)
{
int p, q, f=1;
while(son_left(x) <= n && f)
{
p=son_left(x);
q=son_right(x);
f=0;
if(q<=n && heap[q] < heap[p])
p=q;
if(heap[p] < heap[x])
{
swap1(p, x);
f=1;
}
x=p;
}
}
inline void delete1()
{
swap1(1, n);
n--;
down(1);
}
void heapify()
{
for(int i=n/2;i>=1;--i)
down(i);
}
void heap_Sort(FILE *f)
{
heapify();
while(n)
{
fprintf(f, "%d ", heap[1]);
delete1();
}
}
int main()
{
FILE *fin, *fout;
fin=fopen("algsort.in", "r");
fout=fopen("algsort.out", "w");
n=getInt(fin);
for(int i=1;i<=n;++i)
heap[i]=getInt(fin);
heap_Sort(fout);
fclose(fin);
fclose(fout);
return 0;
}