Cod sursa(job #1739015)

Utilizator moise_alexandruMoise Alexandru moise_alexandru Data 8 august 2016 13:33:13
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.97 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream in("algsort.in");
ofstream out("algsort.out");
const int maxn = 500005;
int v[maxn];
int pos;
int n;

void up(int poz)
{
    if(poz == 0)
        return;
    if(poz / 2 >= 1 && v[poz / 2] < v[poz])
    {
        swap(v[poz], v[poz / 2]);
        up(poz / 2);
    }
    return;
}

void add(int x)
{
    v[++pos] = x;
    up(pos);
}

void down(int poz)
{
    int next = poz * 2;
    if(next < pos && v[next] < v[next + 1])
        next++;

    if(next <= pos && v[poz] < v[next])
    {
        swap(v[poz], v[next]);
        down(next);
    }

    return;
}

int main()
{
    int n, copie;
    in >> n;
    copie = n;
    for(int i = 1; i <= n; i++)
    {
        int x;
        in >> x;
        add(x);
    }
    for(int i = n; i >= 1; i--)
    {
        swap(v[1], v[pos]);
        pos--;
        down(1);
    }
    n = copie;
    for(int i = 1; i <= n; i++)
        out << v[i] << " ";
    out << "\n";
    return 0;
}