标签:
For a nice introduction to counting sort, please refer to 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 namespace std; 6 7 // Counting Sort an Array with each element in [0, upper] 8 void countingSort(vector<int>& nums, int upper) { 9 vector<int> counts(upper + 1, 0); 10 for (int i = 0; i < (int)nums.size(); i++) 11 counts[nums[i]]++; 12 for (int i = 1; i <= upper; i++) 13 counts[i] += counts[i - 1]; 14 vector<int> sorted(nums.size()); 15 for (int i = (int)nums.size() - 1; i >= 0; i--) { 16 sorted[counts[nums[i]] - 1] = nums[i]; 17 counts[nums[i]]--; 18 } 19 swap(nums, sorted); 20 } 21 22 void print(vector<int>& nums) { 23 for (int i = 0; i < (int)nums.size(); i++) 24 printf("%d ", nums[i]); 25 printf("\n"); 26 } 27 28 void countingSortTest(int len, int upper) { 29 vector<int> nums(len); 30 srand((unsigned)time(NULL)); 31 for (int i = 0; i < len; i++) 32 nums[i] = rand() % (upper + 1); 33 print(nums); 34 countingSort(nums, upper); 35 print(nums); 36 } 37 38 int main(void) { 39 countingSortTest(20, 5); 40 system("pause"); 41 return 0; 42 }
If you run this program, you are 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 4 0 1 1 1 2 2 2 3 3 3 3 4 4 4 5 5 5 5 5 5
标签:
原文地址:http://www.cnblogs.com/jcliBlogger/p/4563731.html