Counting sort is a linear time sorting algorithm. It is used when all the numbers fall in a fixed range. Then it counts the appearances of each number and simply rewrites the original array. 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 there.

 #include <iostream>
#include <vector>
#include <ctime> using namespace std; // Counting Sort an Array with each element in [0, upper]
void countingSort(vector<int>& nums, int upper) {
vector<int> counts(upper + , );
for (int i = ; i < (int)nums.size(); i++)
counts[nums[i]]++;
for (int i = ; i <= upper; i++)
counts[i] += counts[i - ];
vector<int> sorted(nums.size());
for (int i = (int)nums.size() - ; i >= ; i--) {
sorted[counts[nums[i]] - ] = nums[i];
counts[nums[i]]--;
}
swap(nums, sorted);
} void print(vector<int>& nums) {
for (int i = ; i < (int)nums.size(); i++)
printf("%d ", nums[i]);
printf("\n");
} void countingSortTest(int len, int upper) {
vector<int> nums(len);
srand((unsigned)time(NULL));
for (int i = ; i < len; i++)
nums[i] = rand() % (upper + );
print(nums);
countingSort(nums, upper);
print(nums);
} int main(void) {
countingSortTest(, );
system("pause");
return ;
}

If you run this program, you are expected to see (I run it on Microsoft Visual Studio Professional 2012):

                   

最新文章

  1. Matlab2015入门学习02
  2. xshell的快捷命令
  3. linux格式批量转换为dos格式
  4. Constructing Roads In JGShining&#39;s Kingdom(HDU1025)(LCS序列的变行)
  5. HDU 5155 Harry And Magic Box --DP
  6. notePad++ 使用
  7. 区间dp的典例
  8. Think Python - Chapter 12 Tuples
  9. uml类关系
  10. SharePoint移动客户端--Rshare 中的Smart Cache
  11. Headfirst设计模式的C++实现——简单工厂模式(Simple Factory)
  12. Http和Socket连接的区别
  13. 关于Hibernate脏检查与快照
  14. Silverlight 5(C#)初探
  15. 云server 性能测试web压力测试
  16. oracle pl/sql中的循环及if语句
  17. vue config.js配置生产环境和发布环境不同的接口地址问题
  18. U盘重装Win10系统视频教程
  19. linux下的别名机制
  20. Django学习笔记之数据库-QuerySet_API

热门文章

  1. 浅谈CSRF攻击方式(转)
  2. FreeBSD Top States
  3. FreeMarker静态化文件解决SEO推广问题
  4. HDOJ 5418 Victor and World 状压DP
  5. Mongodb更新数组$sort操作符
  6. NFC Basics(基本NFC)——翻译自developer.android.com
  7. uva 11400 - Lighting System Design(动态规划 最长上升子序列问题变型)
  8. php-fpm配置详解
  9. 中小企业项目的痛VS感人IT团队
  10. FastDFS 常见问题