#include <iostream> #include <list> #include <vector> using namespace std; //Returns the digit at a particular place in given number int get_digit(int num, int place) { return (num/place)%10; } //Sort the numbers based on the place value //It returns false if no number has a digit in the given place bool counting_sort(vector<int>& nums, int place) { vector<int> count(10); bool more_digits = false; int i; //Divide the numbers into buckets using the place value for( i = 0; i < nums.size(); i++ ) { if( nums[i]/place > 0 ) more_digits = true; count[get_digit(nums[i],place)]++; } if( more_digits ) { //Calculate prefix array to find the actual indices in sorted array for( i = 1; i < 10; i++ ) { count[i] += count[i-1]; } //Use a temp array to store the sorted list vector<int> temp(nums.size()); for( i = nums.size()-1; i >= 0; i-- ) { int ind = get_digit(nums[i],place); if( count[ind] > 0 ) { temp[count[ind]-1] = nums[i]; count[ind]--; } } nums = temp; //Change the original array } return more_digits; } void radix_sort(vector<int>& nums) { //Edge case if( nums.size() < 2 ) return; int place = 1; //For each place, sort numbers using counting sort //stop when there are no more digits at given place while( counting_sort(nums, place) ) place *= 10; } //This implementation uses O(n) extra memory void radix_sort1(vector<int>& nums) { int i; int f = 1; while(true) { bool digits_left = false; vector<list<int>> buckets(10); for(i = 0; i < nums.size(); i++) { int temp = nums[i]/f; if( temp != 0) digits_left = true; buckets[temp%10].push_back(nums[i]); } vector<int> helper(nums.size()); int ind = 0; for(i = 0; i < 10; i++) { list<int>::iterator it; for(it = buckets[i].begin(); it != buckets[i].end(); ++it) helper[ind++] = *it; } nums = helper; if(!digits_left) break; f *= 10; } } int main() { int n; cin >> n; vector<int> nums(n); int i; for(i = 0; i < n; i++) { cin >> nums[i]; } radix_sort(nums); for(i = 0; i < n; i++) cout << nums[i] << " "; return 0; }