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