Cod sursa(job #2897669)

Utilizator pedrosanchezPedro Sanchez pedrosanchez Data 4 mai 2022 14:49:12
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <iostream>
#include <fstream>
#include <array>

const int N = 500001;

using namespace std;

/*ifstream f("input.txt");
ofstream g("output.txt");*/

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

std::array<int, N> c;

void mergeSort(std::array<int, N>& a, int s, int d)
{
    if (s >= d)
    return;
    //cout << s << " " << d << endl;
    int mid = s + (d - s) / 2;
    mergeSort(a, s, mid);
    mergeSort(a, mid + 1, d);

    int cnt = 0;
    int i = s, j = mid + 1;
    //cout << i << " " << j << endl;
    while (i <= mid && j <= d)
    {
       // cout << i << " " << j << endl;
        if (a[i] < a[j])
            {
                c[cnt++] = a[i];
                ++i;
            }else
            {
                c[cnt++] = a[j];
                ++j;
            }
    }

    while (i <= mid)
    c[cnt++] = a[i], ++i;
    while (j <= d)
    c[cnt++] = a[j], ++j;
    for (int i = s; i <= d; ++i)
        a[i] = c[i - s];
}

int main()
{
    std::array<int, N> v;
    int n;
    f >> n;
    for (int i = 0; i < n; ++i)
    {
        f >> v[i];
    }
    mergeSort(v, 0, n - 1);
    for (int i = 0; i < n; ++i)
        g << v[i] << " ";
    
}