Cod sursa(job #1935318)

Utilizator CammieCamelia Lazar Cammie Data 22 martie 2017 10:49:38
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.03 kb
#include <fstream>

#define MAXN 500002

using namespace std;

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

long long heap[MAXN];
int n;

inline void up(int father, int son)
{
    if (father >= 1)
    {
        if (heap[son] > heap[father])
        {
            swap(heap[son], heap[father]);
            up(father / 2, father);
        }
    }
}

inline void down(int father)
{
    int left_son = father * 2;
    int right_son = father * 2 + 1;

    if (left_son <= n)
    {
        if (right_son <= n)
        {
            if (heap[left_son] > heap[father])
            {
                if (heap[right_son] > heap[father])
                {
                    if (heap[right_son] > heap[left_son])
                    {
                        swap(heap[father], heap[right_son]);

                        down(right_son);
                    }
                    else
                    {
                        swap(heap[father], heap[left_son]);

                        down(left_son);
                    }

                }
                else
                {
                    swap(heap[father], heap[left_son]);

                    down(left_son);
                }
            }
            else if (heap[right_son] > heap[father])
            {
                swap(heap[father], heap[right_son]);
                down(right_son);
            }
        }
        else if (heap[left_son] > heap[father])
        {
            swap(heap[left_son], heap[father]);
            down(left_son);
        }
    }
}

inline void Read()
{
    fin >> n;

    for (int i = 1; i <= n; i++)
    {
        fin >> heap[i];

        up(i / 2, i);
    }

    int ii = n; int nn = n;

    while (ii >= 1)
    {
        swap(heap[1], heap[n]);
        n--;

        down(1);

        ii--;
    }

    for (int i = 1; i <= nn; i++)
    {
        fout << heap[i] << " ";
    }
}

int main ()
{
    Read();

    fin.close(); fout.close(); return 0;
}