Cod sursa(job #2871419)

Utilizator preda.andreiPreda Andrei preda.andrei Data 14 martie 2022 18:24:03
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <fstream>
#include <vector>

using namespace std;

constexpr auto kMaxLen = 500'000;
int vec[kMaxLen];

int Partition(int left, int right) {
    auto pivot = vec[(left + right) / 2];

    auto i = left;
    auto j = right;
    while (true) {
        while (vec[i] < pivot) {
            i += 1;
        }
        while (vec[j] > pivot) {
            j -= 1;
        }

        if (i < j) {
            swap(vec[i], vec[j]);
            i += 1;
            j -= 1;
        } else {
            return j;
        }
    }
}

void QuickSort(int left, int right) {
    if (left >= right) {
        return;
    }

    auto mid = Partition(left, right);
    QuickSort(left, mid);
    QuickSort(mid + 1, right);
}

int main() {
    ifstream fin("algsort.in");
    ofstream fout("algsort.out");

    int n;
    fin >> n;
    for (int i = 0; i < n; i += 1) {
        fin >> vec[i];
    }

    QuickSort(0, n - 1);

    for (int i = 0; i < n; i += 1) {
        fout << vec[i] << " ";
    }
    fout << "\n";
    return 0;
}