summaryrefslogtreecommitdiff
path: root/Year_2/Algorithms/ordinamento-lineare.cc
blob: 5af1b1dd4abbbf7ca00a5b51a548b74b8b9e8652 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <fstream>
#include <iostream>
#include <stdlib.h>
#include <string>

using namespace std;

template <typename T>
void
counting_sort(T* A, size_t n, ofstream& fout, int incr, bool is_char = false)
{
    int i, j;
    int max, min;
    int* freq;
    int* t;
    int range;

    for (i = 0; i < n; ++i) {
        A[i] = A[i] * incr;
    }

    max = A[0], min = A[0];
    t = new int[n];

    for (i = 1; i < n; ++i) {
        if (A[i] > max)
            max = A[i];

        if (A[i] < min)
            min = A[i];
    }

    range = (max - min) + 1;

    freq = new int[range];

    for (i = 0; i < range; ++i) {
        freq[i] = 0;
    }

    for (i = 0; i < n; ++i) {
        freq[static_cast<int>(A[i] - min)] += 1;
    }
    for (i = 1; i < range; ++i) {
        freq[i] = freq[i] + freq[i - 1];
    }
    fout << "0 ";
    for (i = 0; i < range - 1; ++i) {
        fout << freq[i] << ' ';
    }

    for (i = n - 1; i >= 0; --i) {
        t[freq[static_cast<int>(A[i] - min)] - 1] = A[i];
        freq[static_cast<int>(A[i] - min)]--;
    }

    for (i = 0; i < n; ++i) {
        A[i] = t[i];
        if (is_char) {
            fout << (char)A[i] << ' ';
        } else {
            fout << A[i] / incr << ' ';
        }
    }
    fout << endl;

    delete[] freq;
    delete[] t;
}

int
main()
{
    ifstream fin("input.txt");
    ofstream fout("output.txt");
    string type;
    int N;

    for (int i = 0; i < 100; ++i) {
        fin >> type;
        fin >> N;

        if (type == "double") {
            double* a = new double[N];

            for (int j = 0; j < N; ++j) {
                fin >> a[j];
            }

            counting_sort(a, N, fout, 10);

            delete[] a;
        } else if (type == "char") {
            char* a = new char[N];

            for (int j = 0; j < N; ++j) {
                fin >> a[j];
            }

            counting_sort(a, N, fout, 1, true);
            delete[] a;
        } else {
            int* a = new int[N];

            for (int j = 0; j < N; ++j) {
                fin >> a[j];
            }

            counting_sort(a, N, fout, 1);
            delete[] a;
        }
    }

    return 0;
}