Cod sursa(job #1703160)

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

using namespace std;

int v[500005],n;

int father(int i){
    return (i>>1);
}

int left(int i){
    if((i<<1) <= n){
        return (i<<1);
    }
    return 0;
}

int right(int i){
    if((i<<1)+1 <= n){
        return (i<<1)+1;
    }
    return 0;
}

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

void descend(int poz){
    while(poz <= n && (v[poz] < v[left(poz)] || v[poz] < v[right(poz)])){
        if(v[left(poz)] > v[right(poz)]){
            swap(v[poz], v[left(poz)]);
            poz = poz<<1;
        }else{
            swap(v[poz], v[right(poz)]);
            poz = (poz<<1)+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;
}