Cod sursa(job #1521643)

Utilizator vladutz15FMI Cornoiu Vlad vladutz15 Data 10 noiembrie 2015 18:48:30
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("algsort.in");
ofstream g("algsort.out");
int n,i,h[500003];
void percolate (int poz)
{
    int val = h[poz];
    while((poz > 1) && (val < h[poz/2]))
    {
        h[poz]=h[poz/2];
        poz/=2;
    }
    h[poz]=val;
}
void sift (int n, int poz)
{
    int son;
    do
    {
        son=0;
        if (poz*2<=n)
        {
            son=poz*2;
            if (poz*2+1<=n && h[poz*2+1] < h[poz*2])
                son=poz*2+1;
            if (h[son]>=h[poz])
                son=0;
        }
        if (son)
        {
            swap(h[poz],h[son]);
            poz=son;
        }
    }
    while(son);
}
int main()
{
    f>>n;
    for(i=1;i<=n;++i)
    {
        f>>h[i];
        percolate(i);
    }
    for (i=n;i>=2;--i)
    {
        g<<h[1]<<" ";
        swap(h[i],h[1]);
        sift(i-1,1);
    }
    g<<h[1];
    return 0;
}