您的位置:首页 > 编程语言 > Go语言

[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.

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: