[Algorithms] Counting Sort

本文深入探讨了计数排序算法的原理、实现过程及其在特定场景下的应用实例。通过提供直观的代码示例,旨在帮助读者理解如何在数组元素处于固定范围时高效排序数据。文中还展示了算法在随机生成的整数数组上的实际运行效果,通过比较排序前后的数组输出,直观验证了算法的有效性和正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

 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

转载于:https://www.cnblogs.com/jcliBlogger/p/4563731.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值