[Algorithms] Radix Sort

本文详细介绍了基数排序算法的原理和实现过程,包括如何使用计数排序作为子过程进行数字从最低有效位到最高有效位的排序,确保算法正确性的前提条件,以及提供了一个C++代码实例。

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

Radix sort is another linear time sorting algorithm. It sorts (using another sorting subroutine) the numbers from their least significant digits to most significant digits. To guarantee the correctness of radix sort, the sorting subroutine must be stable. Moreover, each digit falls in a fixed range. For example, if the numbers are decimal, then all digits fall in [0, 9]. So counting sort is usually used as the subroutine.

The code is as follows. For more on radix sort, please refer to Introduction to Algorithms, 3rd edition.

 1 #include <iostream>
 2 #include <vector>
 3 #include <ctime>
 4 #include <algorithm>
 5 
 6 using namespace std;
 7 
 8 int maximum(vector<int>& nums) {
 9     int mx = nums[0];
10     for (int i = 1; i < (int)nums.size(); i++)
11         mx = max(mx, nums[i]);
12     return mx;
13 }
14 
15 void countingSort(vector<int>& nums, int sig) {
16     vector<int> counts(10, 0);
17     for (int i = 0; i < (int)nums.size(); i++)
18         counts[nums[i] / sig % 10]++;
19     for (int i = 1; i < 10; i++)
20         counts[i] += counts[i - 1];
21     vector<int> sorted(nums.size());
22     for (int i = nums.size() - 1; i >= 0; i--) {
23         sorted[counts[nums[i] / sig % 10] - 1] = nums[i];
24         counts[nums[i] / sig % 10]--;
25     }
26     swap(nums, sorted);
27 }
28 
29 void radixSort(vector<int>& nums) {
30     int mx = maximum(nums);
31     for (int sig = 1; mx / sig; sig *= 10)
32         countingSort(nums, sig);
33 }
34 
35 void radixSortTest(void) {
36     int len = 1000;
37     vector<int> nums(len);
38     srand((unsigned)time(NULL));
39     for (int i = 0; i < (int)nums.size(); i++)
40         nums[i] = rand() % (len + 1);
41     vector<int> copy = nums;
42     radixSort(nums);
43     sort(copy.begin(), copy.end());
44     for (int i = 0; i < (int)nums.size(); i++) {
45         if (nums[i] != copy[i]) {
46             printf("radixSort() test failed!\n");
47             return;
48         }
49     }
50     printf("radixSort() test passed!\n");
51 }
52 
53 int main(void) {
54     radixSortTest();
55     system("pause");
56     return 0;
57 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值