HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcppMinor

Radix sort with C++

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withsortradix

Problem

At first the input array is traversed and for each number the lsb is found. Then the number is put into appropriate bucket according to it. For example for an input array { 123, 45}, at first 123 will be put into bucket 3 (because 123 % 10 == 3). 45 goes to bucket 5. Then after first pass, the input array is cleared and again filled with numbers from the bucket. For the second pass, 123 will be put into bucket 2 and 45 into bucket 4. This continues until the 123 mod is 0.

Can you please review my code?

#include 
#include 
#include 
#include 

class RadixSort
{
public:
    RadixSort(){};
    virtual ~RadixSort(){};

    void sort(std::vector &nums);

private:
    int maxNum,div;
    std::vector > buckets;

};

void RadixSort::sort(std::vector &nums)
{
    if(nums.empty())
        return;

    buckets.resize(10);
    maxNum = *(std::max_element(nums.begin(),nums.end()));

    int i=1;
    while(maxNum != 0)
    {
       // Move numbers into appropriate buckets
       for(auto num : nums)
       {
          if(num&input, const std::vector&output)
{
    RadixSort rs;
    rs.sort(input);
    std::coutinput = {4,90,0};
    std::vectoroutput = {0,4,90};
    test("Test 1",input,output);

    input = {};
    output = {};
    test("Test 2",input,output);

    return 0;
}

Solution

-
With C++11, you can now have right angle brackets together:

std::vector> buckets;


-
If the user will only need to call test(), then sort() can be private.

-
Since sort() throws, its calls may need to be in try blocks so that a caught exception can be handled accordingly. But, first determine if you need it to throw.

-
Some lines like these:

int remainder = (num/i)%10;


can have a little more whitespace:

int remainder = (num / i) % 10;


-
This can be shortened:

if(input == output)
    std::cout<<" passed. ";
else
    std::cout<<" failed. ";


using a single-line ternary statement:

std::cout << ((input == output) ? " passed. " : " failed. ");


You could also append the "\n" to both strings instead of having a separate one.

Moreover, the user may prefer to handle the outcome differently. As such, you may instead have test() return a bool and move the outputs to main(). This should also help keep test() clear of code not involved with the testing.

Code Snippets

std::vector<std::vector<int>> buckets;
int remainder = (num/i)%10;
int remainder = (num / i) % 10;
if(input == output)
    std::cout<<" passed. ";
else
    std::cout<<" failed. ";
std::cout << ((input == output) ? " passed. " : " failed. ");

Context

StackExchange Code Review Q#74541, answer score: 2

Revisions (0)

No revisions yet.