-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcounting_sort.cpp
101 lines (84 loc) · 1.69 KB
/
counting_sort.cpp
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
#include <iostream>
#include <iomanip>
#include <ctime>
#include <cstdlib>
using namespace std;
void create_array(int *&A, int s);
void display_array(int *A, int s, int high);
void populate_array(int *A, int s, int low, int high);
int num_dig(int);
int i_th_dig(int n, int i);
void counting_sort(int *A, int s);
int get_max(int A[], int s);
int main()
{
int *A;
int s = 10;
int l, h;
l = 0;
h = 150563;
cout << "Counting Sort\n";
create_array(A, s);
populate_array(A, s, l, h);
display_array(A, s, h);
counting_sort(A, s);
display_array(A, s, h);
return 0;
}
void create_array(int *&A, int s)
{
A = new int[s];
}
void display_array(int *A, int s, int high)
{
for (int i = 0; i < s; ++i)
{
if (i % 10 == 0)
cout << endl;
cout << setw(num_dig(high) + 2) << A[i];
}
cout << endl;
}
void populate_array(int *A, int s, int low, int high)
{
srand(time(0));
for (int i = 0; i < s; ++i)
{
A[i] = low + rand() % (high + 1 - low);
}
}
int num_dig(int n)
{
if (n < 10)
return 1;
return 1 + num_dig(n / 10);
}
int get_max(int A[], int s)
{
int max = A[0];
for (int i = 1; i < s; i++)
{
if (A[i] > max)
max = A[i];
}
return max;
}
void counting_sort(int *A, int s)
{
int max = get_max(A, s);
int F[max];
int O[max];
for (int i = 0; i <= max; ++i)
F[i] = 0;
for (int i = 0; i < s; i++)
F[A[i]]++;
for (int i = 1; i <= max; i++)
F[i] += F[i - 1];
for (int j = s - 1; j >= 0; j--)
{
O[F[A[j]] - 1] = A[j];
F[A[j]]--;
}
for (int i = 0; i < s; i++)
A[i] = O[i];
}