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 <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>
class RadixSort
{
public:
RadixSort(){};
virtual ~RadixSort(){};
void sort(std::vector<int> &nums);
private:
int maxNum,div;
std::vector<std::vector<int> > buckets;
};
void RadixSort::sort(std::vector<int> &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<0)
throw std::domain_error("For radix sort , array cannot contain negative value. ");
int remainder = (num/i)%10;
buckets[remainder].push_back(num);
}
// Now, move numbers from bucket to original array
nums.clear();
for(auto bucket1:buckets)
{
for(auto bucket2: bucket1)
{
nums.push_back(bucket2);
}
}
for(int j=0; j<10; j++)
{
buckets[j].clear();
}
maxNum/=10;
i *= 10;
}
}
void test(const std::string &testName, std::vector<int>&input, const std::vector<int>&output)
{
RadixSort rs;
rs.sort(input);
std::cout<<testName;
if(input == output)
std::cout<<" passed. ";
else
std::cout<<" failed. ";
std::cout<<"\n";
}
int main()
{
std::vector<int>input = {4,90,0};
std::vector<int>output = {0,4,90};
test("Test 1",input,output);
input = {};
output = {};
test("Test 2",input,output);
return 0;
}