Cod sursa(job #2000250)

Utilizator Ionut.popescuLiviu Rebreanu Ionut.popescu Data 13 iulie 2017 11:13:33
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.99 kb
#include <fstream>

using namespace std;

const int MAXN = 500000;

int a[MAXN], heapSize;

void Swap(int& a, int& b) {
    int t = a;
    a = b;
    b = t;
}

void DownHeap(int node) {
    bool changed;
    int best;
    do {
        best = node;
        changed = false;
        for (int son = 1; son <= 2; ++son)
            if (2 * node + son < heapSize && a[2 * node + son] > a[best])
                best = 2 * node + son;
        
        if (best != node) {
            changed = true;
            Swap(a[node], a[best]);
        }
    } while (changed);
}

int main() {
	ifstream fin("algsort.in");
	ofstream fout("algsort.out");
	int n;
    fin >> n;
    for (int i = 0; i < n; ++i)
        fin >> a[i];

    heapSize = n;
    for (int i = n / 2 - 1; i >= 0; --i)
        DownHeap(i);
    
    for (int i = 0; i < n; ++i) {
        Swap(a[0], a[--heapSize]);
        DownHeap(0);
    }

    for (int i = 0; i < n; ++i)
        fout << a[i] << ' ';
}