I have the following radix sort implementation:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <cstddef>
#include <algorithm>
void radix_sort(std::vector<int>& arr)
{
int radix = 1;
// Largest element in unsorted array
int max = *(std::max_element(arr.begin(), arr.end()));
while(max / radix)
{
// Buckets used for sorting. Each bucket representing a digit.
std::vector<std::vector<int>> buckets(10, std::vector<int>());
for(const auto& num : arr)
{
int digit = num / radix % 10;
buckets[digit].push_back(num);
}
std::size_t k = 0;
// Take the elements out of buckets into the array
for(std::size_t i = 0; i < 10; i++)
{
for(std::size_t j = 0; j < buckets[i].size(); j++)
{
arr[k] = buckets[i][j];
k++;
}
}
// Change the place of digit used for sorting
radix *= 10;
}
}
// Function to print array
void print_arr(std::vector<int>& arr)
{
for(auto elem : arr)
{
std::cout << elem << "\t";
}
std::cout << "\n";
}
int main()
{
std::vector<int> arr;
std::string s;
std::cout << "Enter the elements: " << std::endl;
std::getline(std::cin, s);
std::istringstream ss(s);
int val;
while(ss >> val)
{
arr.push_back(val);
}
std::cout << "Before sorting: \n";
print_arr(arr);
radix_sort(arr);
std::cout << "After sorting: \n";
print_arr(arr);
return 0;
}
I pass an array to the radix_sort
function. It uses a variable called radix
to identify the digit in a particular place (unit, ten, hundred etc.) in the number. Based on this digit, we sort elements into buckets. Once this sorting is done, the elements are taken out based on the order of bucket (The elements in zeroth bucket comes out first, followed by those in first bucket, second bucket and so on). This is repeated until all the digits in the largest element are visited.
1) I would like to know if there is a better data structure for buckets?
2) Is there a more efficient method to find largest element in the unsorted array?
3) If possible, please provide an overall review of the code.