For a nice introduction to counting sort, please refer-Introduction to Alogrithms, 3rd edition. The following code is basically a translation of the pseudo code above.
1#include <iostream>2#include <vector>3#include <ctime>4 5 using namespacestd;6 7 //counting Sort An Array with all element in [0, Upper]8 voidCountingsort (vector<int>& Nums,intUpper) {9vector<int> Counts (upper +1,0);Ten for(inti =0; I < (int) Nums.size (); i++) Onecounts[nums[i]]++; A for(inti =1; I <= Upper; i++) -Counts[i] + = counts[i-1]; -vector<int>Sorted (Nums.size ()); the for(inti = (int) Nums.size ()-1; I >=0; i--) { -Sorted[counts[nums[i]]-1] =Nums[i]; -counts[nums[i]]--; - } + swap (nums, sorted); - } + A voidPrint (vector<int>&nums) { at for(inti =0; I < (int) Nums.size (); i++) -printf"%d", Nums[i]); -printf"\ n"); - } - - voidCountingsorttest (intLenintUpper) { invector<int>nums (len); - Srand ((unsigned) time (NULL)); to for(inti =0; i < Len; i++) +Nums[i] = rand ()% (upper +1); - print (nums); the Countingsort (Nums, upper); * print (nums); $ }Panax Notoginseng - intMainvoid) { theCountingsorttest ( -,5); +System"Pause"); A return 0; the}
If you run the This program, you is expected to see (I run it on Microsoft Visual Studio Professional 2012):
2 3 4 1 5 1 1 5 4 0 3 2 2 5 5 3 5 5 3 40 1 1 1 2 2 2 3 3 3 3 4 4 4 5 5 5 5 5 5
[Algorithms] Counting Sort