Cod sursa(job #3157266)

Utilizator NToniBoSSNicolae Tonitza NToniBoSS Data 14 octombrie 2023 22:49:34
Problema Sortare prin comparare Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 kb
#include <bits/stdc++.h>
using namespace std;

int v[500001], aux[500001], f[500001];

int myselect(int st, int dr, int median){
    /// functia nth_element care face acelasi lucru
    ///nth_element(v + st, v + median, v + dr + 1);
    /// Solutia problema Selectie: Autor: Cristian Francu
    int begin = st;
    int end = dr;
    int aux;
    while ( begin < end ) {
        int b = begin;
        int e = end;
        int pivot = v[(begin + end) / 2]; // alegem un pivot la jumatea vectorului
        while ( v[b] < pivot ) b++;
        while ( v[e] > pivot ) e--;
        while ( b <= e ) {
            aux = v[b]; v[b] = v[e]; v[e] = aux;
            do b++; while(v[b] < pivot);
            do e--; while(v[e] > pivot);
        }
        // acum [begin..e] sint mai mici sau egale cu pivotul
        // si [b..end] sint mai mari sau egale cu pivotul
        if ( median <= e )
            end = e;
        else if ( median >= b )
            begin = b;
        else
            begin = end = median;
    }
}

void mysort(int st, int dr){
    if(st >= dr)
        return ;
    int pivot = (st + dr) / 2;
    myselect(st, dr, pivot);
    int cnt = st;
    for(int i = st; cnt <= pivot && i <= dr; i++)
        if(v[i] <= v[pivot])
            aux[cnt++] = v[i], f[i] = 1;
    for(int i = st; i <= dr; i++)
        if(!f[i])
            aux[cnt++] = v[i];
    for(int i = st; i <= dr; i++){
        f[i] = 0;
        v[i] = aux[i];
        aux[i] = 0;
    }
    mysort(st, pivot);
    mysort(pivot + 1, dr);
}

int main() {
    int i, n;
    freopen("algsort.in", "r", stdin);
    freopen("algsort.out", "w", stdout);
    scanf("%d", &n);
    for(i = 1; i <= n; i++){
        scanf("%d", &v[i]);
    }
    mysort(1, n);
    for(i = 1; i <= n; i++)
        printf("%d ", v[i]);

    return 0;
}