Cod sursa(job #1074256)

Utilizator iordache.bogdanIordache Ioan-Bogdan iordache.bogdan Data 7 ianuarie 2014 13:40:05
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.05 kb
#include <fstream>
using namespace std;

int n,c,i,p,aux;
int v[500005];

int main() {
    ifstream fin("algsort.in");
    ofstream fout("algsort.out");
    fin>>n;
    for (i=1;i<=n;i++) {
        fin>>v[i];
        // am heap cu primele i-1 elemente si tre sa introduc si pe v[i]
        c = i; p =i/2;
        while (p > 0 && v[c] > v[p]) {
            aux = v[c];
            v[c] = v[p];
            v[p] = aux;
            c = p;
            p/=2;
        }
    }

    for (i=n;i>=2;i--) {
        aux = v[i];
        v[i] = v[1];
        v[1] = aux;
        // corectez heap cu i-1 elemente stricat doar de varf

        p = 1;
        c = 2*p;
        while (c <= i-1) {
            if (c+1 <= i-1 && v[c+1] > v[c])
                c++;
            if (v[p] < v[c]) {
                aux = v[p];
                v[p] = v[c];
                v[c] = aux;
            } else
                break;
            p = c;
            c = 2*p;
        }

    }

    for (i=1;i<=n;i++)
        fout<<v[i]<<" ";

    return 0;
}