TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
radix_sort2.cpp
Go to the documentation of this file.
1
24
26
27
#include <algorithm>
28
#include <cassert>
29
#include <cstdint>
30
#include <iostream>
31
#include <vector>
32
37
namespace
sorting
{
43
namespace
radix_sort
{
51
std::vector<uint64_t>
step_ith
(
52
uint16_t cur_digit,
53
const
std::vector<uint64_t>& ar) {
// sorting according to current digit.
54
int
n = ar.size();
55
std::vector<uint32_t> position(10, 0);
56
for
(
int
i = 0; i < n; ++i) {
57
position[(ar[i] / cur_digit) %
58
10]++;
// counting frequency of 0-9 at cur_digit.
59
}
60
int
cur = 0;
61
for
(
int
i = 0; i < 10; ++i) {
62
int
a = position[i];
63
position[i] = cur;
// assingning starting position of 0-9.
64
cur += a;
65
}
66
std::vector<uint64_t> temp(n);
67
for
(
int
i = 0; i < n; ++i) {
68
temp[position[(ar[i] / cur_digit) % 10]] =
69
ar[i];
// storing ar[i] in ar[i]'s cur_digit expected position of
70
// this step.
71
position[(ar[i] / cur_digit) %
72
10]++;
// incrementing ar[i]'s cur_digit position by 1, as
73
// current place used by ar[i].
74
}
75
return
temp;
76
}
77
82
std::vector<uint64_t>
radix
(
const
std::vector<uint64_t>& ar) {
83
uint64_t max_ele =
84
*max_element(ar.begin(), ar.end());
// returns the max element.
85
std::vector<uint64_t> temp = ar;
86
for
(
int
i = 1; max_ele / i > 0;
87
i *= 10) {
// loop breaks when i > max_ele because no further digits
88
// left to makes changes in aray.
89
temp =
step_ith
(i, temp);
90
}
91
for
(uint64_t i : temp) {
92
std::cout << i <<
" "
;
93
}
94
std::cout <<
"\n"
;
95
return
temp;
96
}
97
}
// namespace radix_sort
98
}
// namespace sorting
99
104
static
void
tests
() {
106
std::vector<uint64_t> ar1 = {432, 234, 143, 332, 123};
107
ar1 =
sorting::radix_sort::radix
(ar1);
108
assert(std::is_sorted(ar1.begin(), ar1.end()));
110
std::vector<uint64_t> ar2 = {213, 3214, 123, 111, 112, 142,
111
133, 132, 32, 12, 113};
112
ar2 =
sorting::radix_sort::radix
(ar2);
113
assert(std::is_sorted(ar2.begin(), ar2.end()));
114
}
115
119
int
main
() {
120
tests
();
// execute the tests
121
return
0;
122
}
radix_sort
Functions for Radix sort algorithm.
sorting
for working with vectors
tests
static void tests()
Function to test the above algorithm.
Definition
radix_sort2.cpp:104
sorting::radix_sort::step_ith
std::vector< uint64_t > step_ith(uint16_t cur_digit, const std::vector< uint64_t > &ar)
Function to sort vector according to current digit using stable sorting.
Definition
radix_sort2.cpp:51
sorting::radix_sort::radix
std::vector< uint64_t > radix(const std::vector< uint64_t > &ar)
Function to sort vector digit by digit.
Definition
radix_sort2.cpp:82
main
int main()
Main function.
Definition
radix_sort2.cpp:119
sorting
radix_sort2.cpp
Generated by
1.13.2