Cod sursa(job #1577857)

Utilizator BrandonChris Luntraru Brandon Data 23 ianuarie 2016 22:04:32
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.39 kb
#include <fstream>

using namespace std;

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

int v[500005], merge_v[500005], n;

void read()
{
    cin >> n;
    for(int i = 1; i <= n; ++i)
    {
        cin >> v[i];
    }
}

void merge_interval(int l, int r)
{
    int med = (l + r) / 2;
    int count_int_1 = l, count_int_2 = med + 1, pos = l - 1;
    while(count_int_1 <= med and count_int_2 <= r)
    {
        if(v[count_int_1] <= v[count_int_2])
        {
            ++pos;
            merge_v[pos] = v[count_int_1];
            ++count_int_1;
        }
        else
        {
            ++pos;
            merge_v[pos] = v[count_int_2];
            ++count_int_2;
        }
    }
    for( ; count_int_1 <= med; ++count_int_1)
    {
        ++pos;
        merge_v[pos] = v[count_int_1];
    }
    for( ; count_int_2 <= r; ++count_int_2)
    {
        ++pos;
        merge_v[pos] = v[count_int_2];
    }
    for(int i = l; i <= r; ++i)
    {
        v[i] = merge_v[i];
    }
}

void merge_sort(int l, int r)
{
    if(l == r)
    {
        return ;
    }
    int med = (l + r) / 2;
    merge_sort(l, med);
    merge_sort(med + 1, r);
    merge_interval(l, r);
}

void print()
{
    for(int i = 1; i <= n; ++i)
    {
        cout << v[i] << " ";
    }
}

int main()
{
    read();
    merge_sort(1, n);
    print();
    return 0;
}