Cod sursa(job #2487776)

Utilizator Mihai_PredaPreda Mihai Dragos Mihai_Preda Data 5 noiembrie 2019 18:38:57
Problema Sortare prin comparare Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <random>

using namespace std;

int randBetween(int x, int y)
{
    return rand() % (y - x + 1) + x;
}

void printVector(const vector<int> &v)
{
    for(auto x:v)
        cout << x << " ";
    cout << "\n";
}

void quickSort(vector<int> &v, int start, int stop)
{
    if(start >= stop)
        return;
    int pivot = randBetween(start, stop);
    swap(v[pivot], v[stop]);
    int pivotVal = v[stop];
    int smaller = start;
    for(int i = start; i < stop; ++i)
        if(v[i] < pivotVal)
            swap(v[i], v[smaller++]);
    swap(v[smaller], v[stop]);
    quickSort(v, start, smaller-1);
    quickSort(v, smaller+1, stop);
}

int main()
{
    srand((unsigned int)time(0));
    ifstream in("algsort.in");
    int n;
    in >> n;
    vector<int> v(n);
    for(int &x:v)
        in >> x;
    in.close();
    quickSort(v, 0, n-1);
    
    ofstream out("algsort.out");
    for(int x:v)
        out << x << " ";
    out.close();
    return 0;
}