#include<iostream>
using namespace std;
//获取数组a[]中最大值
int getMax(int a[],int n){
int i,max=0;
for(i=0;i<n;i++){
if(max<a[i])max=a[i];
}
return max;
}
/*
30 * 对数组按照"某个位数"进行排序(桶排序)
31 *
32 * 参数说明:
33 * a -- 数组
34 * n -- 数组长度
35 * exp -- 指数。对数组a按照该指数进行排序。
36 *
37 * 例如,对于数组a={50, 3, 542, 745, 2014, 154, 63, 616};
38 * (01) 当exp=1表示按照"个位"对数组a进行排序
39 * (02) 当exp=10表示按照"十位"对数组a进行排序
40 * (03) 当exp=100表示按照"百位"对数组a进行排序
41 * ...
42 */
void countSort(int a[],int n,int exp){
int output[n]; //
int i,buckets[10]={0};
int temp[n];
//将数据出现次数存储在buckets[]中
for(int i=0;i<n;i++){
buckets[(a[i]/exp)%10]++;
}
//
for(int i=1;i<10;i++){
buckets[i]+=buckets[i-1];
}
for(int i=n-1;i>=0;i--){
output[ buckets[ (a[i]/exp)%10] -1] =a[i];
buckets[(a[i]/exp)%10]--;
}
//
for(int i=0;i<n;i++){
a[i]=output[i];
}
}
void radixSort(int a[],int n){
int exp;
int max=getMax(a,n);
for(exp=1;max/exp>0;exp*=10){
countSort(a,n,exp);
}
}
int main()
{
int i;
int a[] = {53, 3, 542, 748, 14, 214, 154, 63, 616};
int ilen = (sizeof(a)) / (sizeof(a[0]));
cout << "before sort:";
for (i=0; i<ilen; i++)
cout << a[i] << " ";
cout << endl;
radixSort(a, ilen); // 基数排序
cout << "after sort:";
for (i=0; i<ilen; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}
1.10 基数排序 | 菜鸟教程 (runoob.com)这个里面的动态演示就很形象。
可能比较难理解的是
for(int i=1;i<10;i++){
buckets[i]+=buckets[i-1];
}
for(int i=n-1;i>=0;i--){
output[ buckets[ (a[i]/exp)%10] -1] =a[i];
buckets[(a[i]/exp)%10]--;
}
这块,看上面的图就可以知道,刚开始buckets[]数组存的只是个数,那么累加之后不就是整个数组的位置了吗,然后我们从所给待排序数组的倒序开始,一个个按照a[i]/exp%10得出在buckets[]的值,也就是output[]的位置了,不过由于数组位置从0开始得减一。