Cod sursa(job #3245788)

Utilizator obsidianMidnight Majesty obsidian Data 30 septembrie 2024 17:21:55
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <fstream>
using namespace std;

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

#define N_MAX 500000

void swap(int &a, int &b) {
    const int temp = a;
    a = b;
    b = temp;
}

void quick_sort(int a[], int l, int r) {
    int i = l;
    int j = r;
    int mid = (l + r) / 2;
    int pivot = a[mid];

    while (i <= j) {
        // skip from left all the elements < pivot
        while (a[i] < pivot)
            i++;
        // skip from right all the elements > pivot
        while (a[j] > pivot)
            j--;

        // when reaching this point we need to swap the elements
        if (i <= j) {
            swap(a[i], a[j]);
            i++;
            j--;
        }
    }
    if (j > l) {
        quick_sort(a, l, j);
    }
    if (i < r) {
        quick_sort(a, i, r);
    }
}

int main() {
    int n;
    fin >> n;
    int a[N_MAX];
    for (int i = 0; i < n; ++i) {
        fin >> a[i];
    }
    quick_sort(a, 0, n - 1);
    for (int i = 0; i < n; ++i) {
        fout << a[i] << " ";
    }
    return 0;
}