Cod sursa(job #3328325)

Utilizator MateiDiaconuDiaconu Matei Stefan MateiDiaconu Data 7 decembrie 2025 18:28:32
Problema Sortare prin comparare Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <fstream>
#include <vector>

using namespace std;

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

#define MAXN 5000000
#define MAXVAL ((1LL << 31) - 1)
#define NO_PER_BUCKET 1024
#define NO_BUCKETS ((MAXVAL / NO_PER_BUCKET) + 1)


int v[MAXN];
//int freq[NO_BUCKETS];
vector<int> bucket[NO_BUCKETS];


int getBucket(int x){
    return x / NO_PER_BUCKET;
}


void qsort(int ind, int be, int en){
    if(be >= en){
        return;
    }
    int b, e, piv, aux;
    b = be;
    e = en;
    piv = bucket[ind][(b + e) / 2];

    while(bucket[ind][b] < piv){
        b++;
    }
    while(bucket[ind][e] > piv){
        e--;
    }

    while(b < e){
        aux = bucket[ind][b];
        bucket[ind][b] = bucket[ind][e];
        bucket[ind][e] = aux;

        do{
            b++;
        }while(bucket[ind][b] < piv);
        do{
            e--;
        }while(bucket[ind][e] > piv);
    }

    if(be < e){
        qsort(ind, be, e);
    }
    if(e + 1 < en){
        qsort(ind, e + 1, en);
    }
}

int main()
{
    int n, i, j, cnt;

    fin>>n;

    for(i = 0; i < n; i++){
        fin>>v[i];
        bucket[getBucket(v[i])].push_back(v[i]);
    }

    cnt = 0;
    for(i = 0; i < NO_BUCKETS; i++){
        qsort(i, 0, bucket[i].size() - 1);
        for(j = 0; j < bucket[i].size(); j++){
            v[cnt++] = bucket[i][j];
        }
    }

    for(i = 0; i < n; i++){
        fout<<v[i]<<' ';
    }

    fin.close();
    fout.close();
    return 0;
}