Cod sursa(job #966512)

Utilizator Theorytheo .c Theory Data 26 iunie 2013 00:59:31
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.83 kb
//heapsort

#include <fstream>

using namespace std;

ifstream fin ("algsort.in");
ofstream fout ("algsort.out");

const int Nmax = 500009;

int A[Nmax]; int N;


void Read(){

    fin >> N;
    for(int i = 1; i <= N; ++i)
        fin >> A[i];
}

void Percolate(int Pos, int N){

    int NextPos = Pos;

    if( (Pos << 1) <= N && A[NextPos] > A[Pos << 1]) NextPos = (Pos << 1);

    if( (Pos << 1) + 1 <= N &&  A[NextPos] > A[ (Pos << 1) + 1]) NextPos = (Pos << 1) + 1;

    if(Pos != NextPos){

        swap(A[NextPos], A[Pos]);
        Percolate(NextPos, N);
    }
}

void Solve(){

    for(int i = N; i > 0; --i)
        Percolate(i, N);

    while(N){
        fout << A[1] <<" ";
        A[1] = A[N--];
        Percolate(1, N);
    }
}

int main(){

    Read ();

    Solve ();
    return 0;
}