-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathradix_sort2.cpp
More file actions
72 lines (59 loc) 路 1.75 KB
/
Copy pathradix_sort2.cpp
File metadata and controls
72 lines (59 loc) 路 1.75 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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int getMax(vector<string> arr)
{
int max = arr[0].size();
for (int i = 1; i < arr.size(); ++i)
{
if (arr[i].size() > max)
max = arr[i].size();
}
return max;
}
void countingSort(vector<string> &arr, int pos)
{
const int ALPHABET_SIZE = 26;
vector<string> output(arr.size());
vector<int> count(ALPHABET_SIZE, 0);
for (size_t i = 0; i < arr.size(); ++i)
count[arr[i].size() < pos ? 0 : arr[i][arr[i].size() - pos] - 'a' + 1]++;
for (int i = 1; i < ALPHABET_SIZE; ++i)
count[i] = count[i] + count[i - 1];
for (int i = arr.size() - 1; i >= 0; --i)
{
output[count[arr[i].size() < pos ? 0 : arr[i][arr[i].size() - pos] - 'a' + 1] - 1] = arr[i];
count[arr[i].size() < pos ? 0 : arr[i][arr[i].size() - pos] - 'a' + 1]--;
}
for (size_t i = 0; i < arr.size(); ++i)
arr[i] = output[i];
}
void printArray(const vector<string> &arr)
{
for (const auto &str : arr)
cout << str << " | ";
cout << endl;
}
void radixSort(vector<string> &arr)
{
int max = getMax(arr);
cout << "-------------------------------------------------------------------------------------------------" << endl;
for (int pos = 1; pos <= max; pos++)
{
countingSort(arr, pos);
cout << "Pass " << pos << ": ";
printArray(arr);
}
cout << "-------------------------------------------------------------------------------------------------" << endl;
}
int main()
{
vector<string> arr = {"apple", "pears", "mango", "berry", "grape"};
cout << "Before sorting: ";
printArray(arr);
radixSort(arr);
cout << "After sorting: ";
printArray(arr);
return 0;
}