Cod sursa(job #2721506)

Utilizator QwertyDvorakQwerty Dvorak QwertyDvorak Data 11 martie 2021 21:23:48
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <bits/stdc++.h>
using namespace std;

const string FILENAME = "algsort";

ifstream fin(FILENAME + ".in");
ofstream fout(FILENAME + ".out");

int n;
int a[500001];

void heapdown(int dim, int i)
{
    int best = i;
    int st = 2 * i;
    int dr = 2 * i + 1;
    if(st <= dim &&  a[st] > a[best])
        best = st;
    if(dr <= dim && a[dr] > a[best])
        best = dr;
    if(best != i)
    {
        swap(a[i], a[best]);
        heapdown(dim, best);
    }
}

void mySort()
{
    for(int i = n / 2; i >= 1; i--)
        heapdown(n, i);
    for(int i = n; i > 1; i--)
    {
        swap(a[1],  a[i]);
        heapdown(i - 1, 1);
    }

}

int main()
{
    fin >> n;
    for(int i = 1; i <= n; i++)
        fin >> a[i];
    mySort();
    for(int i = 1; i <= n; i++)
        fout << a[i] << " ";
    fout << '\n';
    fin.close();
    fout.close();
    return 0;
}