From c74892191fd8cd7f814ce37c4d876ca8a5a46972 Mon Sep 17 00:00:00 2001 From: Suyash Jaiswal Date: Tue, 13 Oct 2020 00:11:30 +0530 Subject: [PATCH] radix_sort2.cpp --- sorting/radix_sort2.cpp | 115 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 sorting/radix_sort2.cpp diff --git a/sorting/radix_sort2.cpp b/sorting/radix_sort2.cpp new file mode 100644 index 000000000..45c719c44 --- /dev/null +++ b/sorting/radix_sort2.cpp @@ -0,0 +1,115 @@ +/** + * @file + * @brief Algorith of [Radix sort](https://en.wikipedia.org/wiki/Radix_sort) + * @author [Suyash Jaiswal](https://github.com/Suyashjaiswal) + * @details + * Sort the vector of integers using radix sort i.e. sorting digi by digit using count sort as subroutine. + * Running time of radix is O(d*(n+b)) where b is the base for representing numbers and d in the max digits in input inegers and n is number of integers. + * consider example for n = 5, array elements = 432,234,143,332,123 + sorting digit by digit + sorting according to + 1) 1st digit place + => 432,332,143,123,234 + + 2) 2nd digit place + => 123,432,332,234,143 + + 3) 3rd digit place + => 123,143,234,332,432 + + using count sort at each step, which is stable. + stable => already sorted according to previous digits. + +*/ + +// header files +#include +#include +/** + * @namespace sort + * @brief Functions for sorting a vector of integers. + */ +namespace sort +{ +/** + * @namespace radix_sort + * @brief Functions for sorting a vector of integers using radix sort algorithm. + */ + namespace radix_sort + { +/** + * @brief Class to create a vector and sort it. + */ + class radix{ + public: + int n; + std::vector ar; +/** + * @brief Constructor that initializes the vector on creation. + * @param a vector to be sorted. + */ + radix(std::vector& a){ + ar = a; + n = ar.size(); + } + int get_max(){ // returns the max element. + int mx;for(int i = mx = 0;i < n;i++)mx = std::max(mx,ar[i]); + return mx; + } + void show(){ + for(int i = 0;i < n;i++)std::cout< 0;i *= 10){ // loop breaks when i > max_ele because no further digits left to makes changes in array. + step_ith(i); + } +} +} // namespace radix_sort +} // namespace sort + +void test1(){ + std::vector ar = {432,234,143,332,123}; + sort::radix_sort::radix obj(ar); + obj.radix_sort(); + obj.show(); +} +void test2(){ + std::vector ar = {213,3214,123,111,112,142,133,132,32,12,113}; + sort::radix_sort::radix obj(ar); + obj.radix_sort(); + obj.show(); +} +/** + * @brief Main function + * @returns 0 on exit + */ +int main() +{ + test1(); + test2(); + return 0; +} \ No newline at end of file