Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Radix sort Exercises: Sort a collection of integers using the Radix sort

C++ Sorting: Exercise-13 with Solution

Write a C++ program to sort a collection of integers using the Radix sort.

Sample Solution:

C++ Code :

//Ref: https://bit.ly/2rcvXK5
#include <algorithm>
#include <iostream>
#include <iterator>
// Radix sort comparator for 32-bit two's complement integers
class radix_test
{
    const int bit; // bit position [0..31] to examine
public:
    radix_test(int offset) : bit(offset) {} // constructor
 
    bool operator()(int value) const // function call operator
    {
        if (bit == 31) // sign bit
            return value < 0; // negative int to left partition
        else
            return !(value & (1 << bit)); // 0 bit to left partition
    }
};
 
// Least significant digit radix sort
void lsd_radix_sort(int *first, int *last)
{
    for (int lsb = 0; lsb < 32; ++lsb) // least-significant-bit
    {
        std::stable_partition(first, last, radix_test(lsb));
    }
}
 
// Most significant digit radix sort (recursive)
void msd_radix_sort(int *first, int *last, int msb = 31)
{
    if (first != last && msb >= 0)
    {
        int *mid = std::partition(first, last, radix_test(msb));
        msb--; // decrement most-significant-bit
        msd_radix_sort(first, mid, msb); // sort left partition
        msd_radix_sort(mid, last, msb); // sort right partition
    }
}
 
// test radix_sort
int main()
{
    int data[] = {125, 0, 695, 3, -256, -5, 214, 44, 55};

    std::cout << "Before Sorting:" << std::endl;

    std::copy(data, data + 8, std::ostream_iterator<int>(std::cout, " "));
 
    lsd_radix_sort(data, data + 8);
    // msd_radix_sort(data, data + 8);
    std::cout << "\nAfter Sorting:" << std::endl;
    std::copy(data, data + 8, std::ostream_iterator<int>(std::cout, " "));
     return 0;
}

Sample Output:

Before Sorting:
125 0 695 3 -256 -5 214 44 
After Sorting:
-256 -5 0 3 44 125 214 695 

Flowchart:

Flowchart: Sort a collection of integers using the Radix sort

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to sort a collection of integers using the Quick sort.
Next: Write a C++ program to sort a collection of integers using the Selection sort.

What is the difficulty level of this exercise?