Cod sursa(job #2862411)

Utilizator Toaster_KeyboardMihaescu Vlad-Mihai Toaster_Keyboard Data 5 martie 2022 12:59:11
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#pragma region
#include <bits/stdc++.h>
using namespace std;
// File
ifstream fin("algsort.in");
ofstream fout("algsort.out");
#pragma endregion

void merge(vector<int>& vect, int lhs, int mid, int rhs) {
    int lhSize = mid - lhs + 1;
    int rhSize = rhs - mid;
    vector<int> lhsVect(lhSize), rhsVect(rhSize);
    for (int i = 0; i < lhSize; i++)
        lhsVect[i] = vect[lhs + i];
    for (int i = 0; i < rhSize; i++) {
        rhsVect[i] = vect[mid + 1 + i];
    }

    int indexL = 0, indexR = 0;
    int indexF = lhs;
    while (indexL < lhSize && indexR < rhSize) {
        if (lhsVect[indexL] > rhsVect[indexR])
            vect[indexF] = rhsVect[indexR], indexR++;
        else vect[indexF] = lhsVect[indexL], indexL++;
        indexF++;
    }
    while (indexL < lhSize) {
        vect[indexF] = lhsVect[indexL];
        indexL++;
        indexF++;
    }
    while (indexR < rhSize) {
        vect[indexF] = rhsVect[indexR];
        indexR++;
        indexF++;
}
}

void mergeSort(vector<int>& vect, int lhs, int rhs) {
    int mid = lhs + (rhs - lhs) / 2;
    if (rhs > lhs) {
        mergeSort(vect, lhs, mid);
        mergeSort(vect, mid + 1, rhs);
        merge(vect, lhs, mid, rhs);
    }
}

int main() {
    ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    int n;
    fin >> n;

    vector<int> vect(n);
    for (auto& it : vect)
        fin >> it;

    mergeSort(vect, 0, n - 1);

    for (auto it : vect)
        fout << it << ' ';
    return 0;
}