-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountingSort_Int.cpp
More file actions
75 lines (62 loc) · 1.27 KB
/
CountingSort_Int.cpp
File metadata and controls
75 lines (62 loc) · 1.27 KB
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
#include <iostream>
using namespace std;
class CountingSort {
int* A;
int dim;
int AddElement(int x);
public:
CountingSort(int dim) {
this->dim = dim;
A = new int();
for (int i = 0; i < dim; i++)
A[i] = AddElement(i);
}
void Sort();
void Print();
int getMax();
int getMin();
};
int CountingSort::getMax() {
int max = A[0];
for (int i = 1; i < dim; i++)
if (max < A[i]) max = A[i];
return max;
}
int CountingSort::getMin() {
int min = A[0];
for (int i = 1; i < dim; i++)
if (min > A[i]) min = A[i];
return min;
}
int CountingSort::AddElement(int x) {
int temp;
cout << "Add a new element n." << x + 1 << " @> ";
cin >> temp;
return temp;
}
void CountingSort::Sort() {
int max = getMax();
int min = getMin();
int range = max - min + 1;
int* C = new int[range];
for (int i = 0; i <= range; i++)
C[i] = 0;
for (int i = 0; i < dim; i++)
C[A[i] - min]++;
for (int i = 1; i <= range; i++)
C[i] += C[i - 1];
int B[dim];
for (int i = dim - 1; i >= 0; i--) {
B[C[A[i] - min] - 1] = A[i];
C[A[i] - min]--;
}
for (int i = 0; i < dim; i++)
A[i] = B[i];
}
void CountingSort::Print() {
cout << endl;
for (int i = 0; i < dim; i++)
cout << A[i] << " ";
cout << endl
<< endl;
}