Pagini recente » Cod sursa (job #2982620) | Cod sursa (job #2768533) | Cod sursa (job #814438) | Cod sursa (job #2372984) | Cod sursa (job #2294120)
#include<fstream>
#include<vector>
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int n;
int heap[200001];
int length = 0;
inline int father(int x){
return x>>1;
}
inline int left_son(int x){
return x<<1;
}
inline int right_son(int x){
return (x<<1)+1;
}
void heap_up(int x){
int val = heap[x];
while( x > 1 && val < heap[father(x)]){
swap(heap[x], heap[father(x)]);
x = father(x);
}
}
void heap_down(int x){
int son = 1;
while(son){
son = 0;
if(left_son(x) <= length){
son = left_son(x);
if(right_son(x) <= length && heap[right_son(x)] < heap[left_son(x)]){
son = right_son(x);
}
if(heap[son] >= heap[x])
son = 0;
}
if(son){
swap(heap[son], heap[x]);
x = son;
}
}
}
int main()
{
freopen("algsort.in", "r", stdin);
freopen("algsort.out", "w", stdout);
int operatie;
int x, k = 0;
scanf("%d", &n);
for(int i = 1 ; i <= n ; i++){
scanf("%d", &x);
heap[i] = x;
}
length = n;
for(int i = n / 2 ; i >= 1 ; i--)
heap_down(i);
for(int i = n ; i >= 1 ; i--){
printf("%d ", heap[1]);
swap(heap[1], heap[length]);
length --;
heap_down(1);
}
return 0;
}