[Algorithms] Radix Sort
2015-06-09 20:48
423 查看
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.
The code is as follows. For more on radix sort, please refer to Introduction to Algorithms, 3rd edition.
#include <iostream> #include <vector> #include <ctime> #include <algorithm> using namespace std; int maximum(vector<int>& nums) { int mx = nums[0]; for (int i = 1; i < (int)nums.size(); i++) mx = max(mx, nums[i]); return mx; } void countingSort(vector<int>& nums, int sig) { vector<int> counts(10, 0); for (int i = 0; i < (int)nums.size(); i++) counts[nums[i] / sig % 10]++; for (int i = 1; i < 10; i++) counts[i] += counts[i - 1]; vector<int> sorted(nums.size()); for (int i = nums.size() - 1; i >= 0; i--) { sorted[counts[nums[i] / sig % 10] - 1] = nums[i]; counts[nums[i] / sig % 10]--; } swap(nums, sorted); } void radixSort(vector<int>& nums) { int mx = maximum(nums); for (int sig = 1; mx / sig; sig *= 10) countingSort(nums, sig); } void radixSortTest(void) { int len = 1000; vector<int> nums(len); srand((unsigned)time(NULL)); for (int i = 0; i < (int)nums.size(); i++) nums[i] = rand() % (len + 1); vector<int> copy = nums; radixSort(nums); sort(copy.begin(), copy.end()); for (int i = 0; i < (int)nums.size(); i++) { if (nums[i] != copy[i]) { printf("radixSort() test failed!\n"); return; } } printf("radixSort() test passed!\n"); } int main(void) { radixSortTest(); system("pause"); return 0; }
相关文章推荐
- Error Code: 1318. Incorrect number of arguments for PROCEDURE company.new_procedure; expected 2, got
- Error Code: 1318. Incorrect number of arguments for PROCEDURE company.new_procedure; expected 2, got
- Google Web Toolkit(GWT) 在windows下环境搭建
- Google三大论文简单摘要
- good
- google guava中定义的String操作
- 欢迎使用CSDN-markdown编辑器
- django-groundwork
- 不是语言之争--Go vs Erlang
- Go vs Erlang
- Go实践
- Category
- webgoat实验记录
- Codeforces 39E What Has Dirichlet Got to Do with That? 游戏+内存搜索
- go语言defer使用 .
- [Algorithms] Counting Sort
- 二维码之qrencode生成(带logo)
- mac修改host文件,让你的mac轻松上google
- golang语法学习(一):变量,常量以及数据类型
- golang vim ide 环境搭建