Cod sursa(job #753580)

Utilizator mihai995mihai995 mihai995 Data 30 mai 2012 00:28:47
Problema Sortare prin comparare Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <fstream>
using namespace std;

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

struct Nod
{
    int val;
    Nod* next;

    Nod()
    {
        val = 0;
        next = NULL;
    }

    Nod(int _val, Nod* _next)
    {
        val = _val;
        next = _next;
    }
};

Nod* insert(Nod* p, int x)
{
    return p -> next = new Nod(x, p -> next);
}

Nod* find_mid(Nod* st, Nod* dr)
{
    if (st == dr || st -> next == dr)
        return st;

    Nod* m = st;

    st = st -> next -> next;

    while (st)
    {
        m = m -> next;

        st = st -> next;

        if (st)
            st = st -> next;
    }

    return m;
}

Nod* sort(Nod* st, Nod* dr)
{
    if (st == dr)
        return st;

    Nod *m = find_mid(st, dr), *rez = new Nod, *unde, *a, *b;

    b = sort(m -> next, dr);

    m -> next = NULL;

    a = sort(st, m);

    unde = rez;

    while (a || b)
        if (!b || (a && a -> val <= b -> val))
        {
            unde -> next = a;
            unde = a;
            a = a -> next;
        }
        else
        {
            unde -> next = b;
            unde = b;
            b = b -> next;
        }

    return rez -> next;
}

Nod* create()
{
    Nod *st, *dr;
    st = dr = new Nod;

    int n, x;

    in >> n;

    while (n--)
    {
        in >> x;
        dr = insert(dr, x);
    }

    return sort(st -> next, dr);
}

void print(Nod* lista)
{
    for (Nod* p = lista ; p ; p = p -> next)
        out << p -> val << " ";

    out << "\n";
}

int main()
{
    print(create());

    return 0;
}