Cod sursa(job #1512456)

Utilizator Narcys01Ciovnicu Narcis Narcys01 Data 28 octombrie 2015 08:42:33
Problema Sortare prin comparare Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int n;
int h[100005];

void Sift(int k)
{
    int son = 0;
    do
    {
        son = 0;
        if (k * 2 <= n)
        {
            son = k * 2;
            if (2 * k + 1 <= n && h[2*k] < h[2*k+1])
                son = k * 2 + 1;
            if (h[son] <= h[k])
                son = 0;
        }
        if (son)
        {
            swap(h[son], h[k]);
            k = son;
        }
    } while (son);
}

void Build_H()
{
    int i;
    for (i = n / 2; i > 0; i--)
        Sift(i);
}

void Sort_H()
{
    Build_H();
    int i, N;
    N = n;
    for (i = n; i >= 2; i--)
    {
        swap(h[1], h[i]);
        n--;
        Sift(1);
    }
    n = N;
}

int main()
{
    int i;
    fin >> n;
    for (i = 1; i <= n; i++)
        fin >> h[i];
    Sort_H();
    for (i = 1; i <= n; i++)
        fout << h[i] << " ";
    return 0;
}