Cod sursa(job #1780363)

Utilizator SlevySlevoaca Stefan-Gabriel Slevy Data 16 octombrie 2016 02:16:18
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
#define NMAX 500001
#define BUFF_SIZE 100000

using namespace std;

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

int a[NMAX], aux[NMAX], n;
char BUFF[BUFF_SIZE];
int pos = 0;

void Read(int &a)
{
    while (!isdigit(BUFF[pos]))
        if (++pos == BUFF_SIZE)
         in.read(BUFF,BUFF_SIZE), pos = 0;
    a = 0;
    while (isdigit(BUFF[pos]))
    {
        a = a * 10 + BUFF[pos] - '0';
        if (++pos == BUFF_SIZE)
         in.read(BUFF,BUFF_SIZE), pos = 0;
    }
}

void Merge(int xa, int ya, int xb, int yb)
{
    int i = xa, j = xb;
    int k = 0;
    while (i <= ya && j <= yb)
    {
        if (a[i] < a[j])
            aux[++k] = a[i++];
        else if (a[i] > a[j])
            aux[++k] = a[j++];
        else
        {
            aux[++k] = a[i++];
            aux[++k] = a[j++];
        }
    }
    while (i <= ya)
        aux[++k] = a[i++];
    while (j <= yb)
        aux[++k] = a[j++];
}

void MergeSort(int x, int y)
{
    int m;
    if (x != y)
    {
        m = x + ((y - x) / 2);
        MergeSort(x, m);
        MergeSort(m + 1, y);
        Merge(x, m, m + 1, y);
        for(int i = x; i <= y; i++)
            a[i] = aux[i - x + 1];
    }
}

int main()
{
    Read(n);
    for (int i = 1; i <= n; i++)
        Read(a[i]);
    in.close();
    MergeSort(1,n);
    for (int i = 1; i <= n; i++)
        out << a[i] << " ";
    out.close();
    return 0;
}