Pagini recente » Cod sursa (job #66578) | Borderou de evaluare (job #1844103) | Cod sursa (job #815297) | Cod sursa (job #689773) | Cod sursa (job #644086)
Cod sursa(job #644086)
#include<fstream>
using namespace std;
const int MAX_HEAP_SIZE=500000;
typedef int heap[MAX_HEAP_SIZE];
ifstream f("algsort.in");
ofstream g("algsort.out");
int N;
heap H;
int father(int nod){
return nod/2;
}
int left_son(int nod){
return 2*nod;
}
int right_son(int nod){
return 2*nod+1;
}
int maxim(heap H){
return H[1];
}
void sift(heap H,int N,int k){
int son;
do{
son=0;
if(left_son(k)<=N){
son=left_son(k);
if(right_son(k)<=N&&H[right_son(k)]>H[left_son(k)])
son=right_son(k);
if(H[son]<=H[k])
son=0;
}
if(son){
swap(H[son],H[k]);
k=son;
}
}
while(son);
}
void percolate(heap H,int N,int k){
int key=H[k];
while((k>1)&&(key>H[father(k)])){
H[k]=H[father(k)];
k=father(k);
}
H[k]=key;
}
void build_heap(heap H,int N){
for(int i=N/2;i>0;--i)
sift(H,N,i);
}
void heapsort(heap H,int N){
build_heap(H,N);
for(int i=N;i>=2;--i){
swap(H[1],H[i]);
sift(H,i-1,1);
}
}
int main(){
f>>N;
for(int i=1;i<=N;i++)
f>>H[i];
heapsort(H,N);
for(int i=1;i<=N;i++)
g<<H[i]<<" ";
return 0;
}