Cod sursa(job #2079282)

Utilizator xkz01X.K.Z. xkz01 Data 30 noiembrie 2017 21:52:48
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.9 kb
///HEAPSORT
#include<cstdio>
#include<algorithm>
using namespace std;
int i, heap[500001], n, x, lgHeap;
void heap_up(int poz){
    while (poz>1) {
        if (heap[poz]<heap[poz/2]) {swap(heap[poz], heap[poz/2]); poz/=2;}
            else break;
    }
}
void heap_down(int poz){
    int son;
    while (2*poz<=lgHeap) {
        if (2*poz+1>lgHeap) son=2*poz;
            else {if (heap[2*poz]<=heap[2*poz+1]) son=2*poz; else son=2*poz+1;}
        if (heap[son]<heap[poz]) {swap(heap[son], heap[poz]); poz=son;}
            else return;
    }
}
int main(){
    freopen("algsort.in","r",stdin);
    freopen("algsort.out","w",stdout);
    scanf("%d", &n);
    for (i=1;i<=n;i++) {scanf("%d", &x); heap[++lgHeap]=x; heap_up(lgHeap);}
    for (i=1;i<=n;i++) {
        printf("%d ", heap[1]);
        swap(heap[1], heap[lgHeap]);
        lgHeap--;
        heap_down(1);
    }
    return 0;
}