Cod sursa(job #2950075)

Utilizator guzgandemunteIonescu Laura guzgandemunte Data 2 decembrie 2022 19:21:47
Problema Sortare prin comparare Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <iostream>
#include <fstream>
#define NMAX 500000

using namespace std;

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

int v[NMAX];

int lomutoPartition(int lo, int hi) {
    int pivot = v[hi];
    int curr = lo - 1;
    int tmp;

    for (int i = lo; i < hi; ++i) {
        if (v[i] <= pivot) {
            // increment curr and swap a[i] with a[curr]
            ++curr;
            tmp = v[i], v[i] = v[curr], v[curr] = tmp;
        }
    }

    tmp = v[curr + 1], v[curr + 1] = v[hi], v[hi] = tmp;

    return curr + 1;
}

void quickSort(int lo, int hi) {
    if (lo < hi) {
        int pivotIndex = lomutoPartition(lo, hi);
        quickSort(lo, pivotIndex - 1);
        quickSort(pivotIndex + 1, hi);
    }
}

int main()
{
    ios_base::sync_with_stdio(false);

    fin.tie(NULL);
    fout.tie(NULL);

    int n;
    fin >> n;

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

    quickSort(0, n - 1);
    
    for (int i = 0; i < n; ++i) {
        fout << v[i] << " ";
    }
}