Cod sursa(job #1493097)

Utilizator Burbon13Burbon13 Burbon13 Data 28 septembrie 2015 18:50:50
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#include <cstdio>
#include <iostream>
#define nmx 500002
using namespace std;

int n, nr, h[nmx];

void percolate(int pos){
    if(pos > 1 && h[pos] < h[pos/2]){
        swap(h[pos],h[pos/2]);
        percolate(pos/2);
    }
}

void sift(int pos){
    int fiu;
    if(2 * pos <= n){
        fiu = h[2*pos];
        if(2 * pos + 1 <= n && h[2*pos+1] < fiu && fiu < h[pos]){
            swap(h[pos],h[2*pos+1]);
            sift(2*pos+1);
            return;
        }
        if(fiu < h[pos]){
            swap(h[pos],h[2*pos]);
            sift(2*pos);
        }
    }
}

int main(){
    freopen("algsort.in", "r", stdin);
    freopen("algsort.out", "w", stdout);

    scanf("%d", &n);
    for(int i = 1; i <= n; ++i){
        scanf("%d", &nr);
        h[i] = nr;
        percolate(i);
    }

    for(n; n > 0; --n){
        printf("%d ", h[1]);
        h[1] = h[n];
        sift(1);
    }

    return 0;
}