Cod sursa(job #1703159)

Utilizator alittlezzCazaciuc Valentin alittlezz Data 16 mai 2016 13:49:16
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include <stdio.h>
#include <algorithm>
#include <math.h>

using namespace std;

int v[500005],n;

void ascend(int poz){
    while(poz > 1 && v[poz] > v[poz>>1]){
        swap(v[poz], v[poz>>1]);
        poz >>= 1;
    }
}

void descend(int poz){
    while(poz <= n && (v[poz] < v[(poz*2 <= n ? poz*2 : 0)] || v[poz] < v[(poz*2+1 <= n ? poz*2+1 : 0)])){
        if(v[(poz*2 <= n ? poz*2 : 0)] > v[(poz*2+1 <= n ? poz*2+1 : 0)]){
            swap(v[poz], v[(poz*2 <= n ? poz*2 : 0)]);
            poz = poz*2;
        }else{
            swap(v[poz], v[(poz*2+1 <= n ? poz*2+1 : 0)]);
            poz = poz*2+1;
        }
    }
}

int main()
{
    freopen("algsort.in", "r", stdin);
    freopen("algsort.out", "w", stdout);
    int i;
    scanf("%d",&n);
    for(i = 1;i <= n;i++){
        scanf("%d",&v[i]);
        ascend(i);
    }
    int nn = n;
    for(;n;){
        int ax = v[1];
        v[1] = v[n];
        v[n] = ax;
        n--;
        descend(1);
    }
    for(i = 1;i <= nn;i++){
        printf("%d ",v[i]);
    }
    return 0;
}