对于基数排序不理解的可以看这篇文章:点击打开链接
还有这篇关于计数排序、桶排序、基数排序的比较:点击打开链接
基数排序与桶排序的不同:
(1)桶排序是将数据映射成不同的桶,每个桶代表所有数据的一个子区间,然后在每个桶内使用O(nlogn)的排序方法,从从而减少元素之间的比较次数。当每个桶内只有一个元素时,完全消除元素之间的比较,从而时间复杂度能够达到O(n)。显然,这是用空间换时间的明显转换。
(2)基数排序的思想就是将待排数据中的每组关键字依次进行桶分配。每轮桶分配完成再重新收集到原始数组中取。数据从低位到高位的十进制0-9的数可以作为每轮桶分配的关键字,关键字相同的分配到同一个桶中。依次从数据的低位十进制数到高位进行每一轮的桶分配和收集。
下面是本人的实现,通过stl的容器vector存放待排序数据,以及vector<list<int>>存放每个桶。getshuf()函数产生0-n范围内的非重复整数。
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <ctime>
using namespace std;
vector<int> getshuf(int m, int n)
{
if (m > n)
{
throw runtime_error("Error: not enough numbers of array range\n");
}
vector<int> temp(n);
int i = 0;
//初始化随机数组
for_each(temp.begin(), temp.end(), [&i](int& x)
{
x = i++;
});
srand((unsigned)time(NULL));
//打乱0-m-1的元素
for (i = 0; i < m; ++i)
{
swap(temp[i], temp[rand() % (n - 1 - i) + i]);
}
return vector<int>(temp.begin(), temp.begin() + m);
}
void radixSort(vector<int>& vec, int maxval)
{
if (vec.empty())
{
throw runtime_error("Error; empty array!\n");
return;
}
vector<list<int>> bucket(10);
int step = 1;
while (maxval / 10)
{
maxval = maxval/10;
++step;
}
for (int i = 1; i <= step; ++i)
{
//分配
for (int j = 0; j < vec.size(); ++j)
{
int bitnum = vec[j];
for (int k = 1; k < i; ++k)
{
bitnum /= 10;
}
bitnum %= 10;
bucket[bitnum].push_back(vec[j]);
}
//收集
int count = 0;
for (int j = 0; j < bucket.size(); ++j)
{
for (list<int>::iterator iter = bucket[j].begin(); iter != bucket[j].end(); ++iter)
{
vec[count++] = *iter;
}
if (!bucket.empty())
bucket[j].clear();
}
}
}
int main(int argc, char** argv)
{
int m = 1000, n = 10000;
vector<int> vec = getshuf(m, n);
cout<<"Before radixSort, vec = ["<<endl;
for_each(vec.begin(), vec.end(), [](int x)
{
cout<<x<<' ';
});
cout<<']'<<endl;
radixSort(vec, n);
cout<<"After radix sort, vec = ["<<endl;
for_each(vec.begin(), vec.end(), [](int x)
{
cout<<x<<' ';
});
cout<<']'<<endl;
return 0;
}