Cod sursa(job #2726436)

Utilizator AkrielAkriel Akriel Data 20 martie 2021 22:28:27
Problema Sortare prin comparare Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>

using namespace std;

const int minConst = 1024;

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

vector<int> initialNumbers;

double EPS = 1e-6;

void akySort(vector<int>& numbers){
    if (numbers.size() < minConst){
        sort(numbers.begin(), numbers.end());
        return;
    }

    int maxValue = numbers[0];
    int minValue = numbers[0];
    for (auto const &el : numbers){
        maxValue = max(maxValue, el);
        minValue = min(minValue, el);
    }

    int fragments = sqrt(maxValue-minValue);
    double step = (double)(maxValue-minValue) / (double)(fragments);
    auto* buckets = new vector<int>[fragments];
    for (auto const &el : numbers){
        int index = max(min((int)((el-minValue) / step), fragments-1), 0);
        buckets[index].push_back(el);
    }

    vector<int> result;
    for (int i = 0; i < fragments; i++){
        if (buckets[i].size() == numbers.size()){
            // sort(bucket.begin(), bucket.end());
            goto push_elem;
        }

        akySort(buckets[i]);

        push_elem:
        for (auto & el : buckets[i]){
            result.push_back(el);
        }
    }
    numbers = result;
}

int main() {
    int n = 1e5;
    fin >> n;
    initialNumbers.resize(n);
    for (auto &el : initialNumbers){
        fin >> el;
//        el = rand();
    }
    akySort(initialNumbers);
//     cout << is_sorted(initialNumbers.begin(), initialNumbers.end());
    for (auto &el : initialNumbers){
        fout << el << " ";
    }
    return 0;
}