Cod sursa(job #3137774)

Utilizator chiriacandrei25Chiriac Andrei chiriacandrei25 Data 14 iunie 2023 20:49:00
Problema Sortare prin comparare Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <fstream>
#include <stdlib.h>
#include <time.h>

using namespace std;

const int Nmax = 500005;

int a[Nmax], n;

void quickSort(int left, int right) {
    if(left >= right) {
        return;
    }
    // a = [1 20 10], pivot = 2
    int pivot = a[left + rand() % (right - left + 1)];
    int i = left, j = right;

    while(i < j) {
        if(a[i] < pivot) {
            i++;
        }
        else if(a[j] > pivot) {
            j--;
        }
        else {
            swap(a[i++], a[j--]);
        }
    }
    quickSort(left, i - 1);
    quickSort(i, right);
}

int main() {
    ifstream fin("algsort.in");
    ofstream fout("algsort.out");
    fin >> n;
    for(int i = 1; i <= n; i++) {
        fin >> a[i];
    }

    srand(time(NULL)); // ca functia rand() sa genereze random bine

    quickSort(1, n);
    for(int i = 1; i <= n; i++) {
        fout << a[i] << " ";
    }
    fout << "\n";
}