码迷,mamicode.com
首页 > 其他好文 > 详细

[Algorithms] Counting Sort

时间:2015-06-09 17:01:26      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

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

[Algorithms] Counting Sort

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4563731.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!