/*具体原理:从低位到高位对输入数据个位数字一次进行计数排序*/
#include "stdafx.h"
#include<iostream>
using namespace std;
int Location_num(int in,int location){//求一个数的第location位数字
int temp = 1;
for(int i = 0;i < location-1;++i)temp *= 10;
return (int)((in%(10*temp))/temp);
}
void Count_sort(int *out,int *in,int location,int length){//依据第locaton位数字进行计数排序
int a[10];
for(int i = 0;i < 10;++i){
a[i] = 0;
}
for(int i = 0;i < length;++i){
++a[Location_num(in[i],location)];
}
for(int i = 0;i < 9;++i){
a[i+1] += a[i];
}
for(int i = length-1;i > -1;--i){
out[--a[Location_num(in[i],location]] = in[i];
}
}
int *Radix_sort(int *in,int length,int maxwidth){//基数排序实现
int *Out = new int[length];
for(int i = 2;i <= maxwidth;++i){
Count_sort(Out,in,i,length);
for(int j = 0;j <= length-1;++j){//按照从低位到高位分别进行一次计数排序
in[j] = Out[j];
}
}
delete[] Out;
return in;
}
void main(){
/*基数排序测试数据*/
int p[] = {
123,456,789,456,
654,987,321,369,
258,147,741,852,
966,48,5,54,6,56,
45654,6,54,9,54,
665,665,5454,45,
54,54,6,45654,32,
132,213,123,123,
465,654,654,564,
654,56,4654,465,
456465,458
};
int length = sizeof(p)/sizeof(int);
Radix_sort(p,length,6);
for(int i = 0;i < length;++i)cout<<p[i]<<" ";//显示排序结果
cout<<endl<<endl;
}