基数排序C++的实现排序分为两个部分,分配(distribute)和收集(colect)两个部分,基数排序就是按照关键字来排序,就比如对数字进行进行排序关键字就是个位、十位等等,一般是低位排序。这里的实例就是对两位数的进行排序的,这里的程序写得不够灵活,需要修改的地方非常多,仅做参考。这里写出的程序已经固定死了只能排序0-99的整数,缺少灵活性,如若需要同时排序多位数的数则课添加判断关键个数的代码。
#include<iostream>
#include<cmath>
using namespace std;
struct list
{
int e;
int next;
};
void MyDistribute(list node[],int n,int r,int d,int i,int f[],int e[])
{
int j,index,power;
for(j=0;j<r;j++)
f[j]=-1;
for(power=(int)pow((double)r,i-1),index=node[0].next;index!=-1;index=node[index].next)
{
j=(node[index].e/power)%r;
if(f[j]==-1) f[j]=index;
else node[e[j]].next=index;
e[j]=index;
}
}
void MyColect(list node[],int n,int r,int d,int i,int f[],int e[])
{
int j,t;
int first=true;
for(j=0;j<r;j++)
{
if(f[j]!=-1)
{
if(first)
{
node[0].next=f[j];
first=false;
}
else
{
node[t].next=f[j];
}
t=e[j];
}
}
node[t].next=-1;
}
void Myradixsort(int elem[],int n,int r,int d)
{
list *node;
int *f,*e;
int i,p;
node=new list[n+1];
f=new int[r];
e=new int[r];
for(i=1;i<=n;i++)
{
node[i].e=elem[i-1];
node[i].next=i+1;
}
node[0].next=1;
node[n].next=-1;
for(i=1;i<=d;i++)
{
MyDistribute(node, n,r,d,i,f,e);
MyColect(node,n,r,d,i,f,e);
}
p=node[0].next;
for(i=0;i<n;i++)
{
elem[i]=node[p].e;
p=node[p].next;
}
delete []f;
delete []e;
delete []node;
}
int main(){
int *a;
int size=10;
int pos;
a=new int[size];
int b[10]={23,12,14,11,10,13,56,45,11,10};
cout<<"排序前的数列:";
for(int k=0;k<10;k++)
cout<<b[k]<<" ";
cout<<endl;
Myradixsort(b,size,10,2);
cout<<"排序后的数列:";
for(int l=0;l<10;l++)
cout<<b[l]<<" ";
cout<<endl;
delete []a;
return 0;
}
#include<cmath>
using namespace std;
struct list
{
int e;
int next;
};
void MyDistribute(list node[],int n,int r,int d,int i,int f[],int e[])
{
int j,index,power;
for(j=0;j<r;j++)
f[j]=-1;
for(power=(int)pow((double)r,i-1),index=node[0].next;index!=-1;index=node[index].next)
{
j=(node[index].e/power)%r;
if(f[j]==-1) f[j]=index;
else node[e[j]].next=index;
e[j]=index;
}
}
void MyColect(list node[],int n,int r,int d,int i,int f[],int e[])
{
int j,t;
int first=true;
for(j=0;j<r;j++)
{
if(f[j]!=-1)
{
if(first)
{
node[0].next=f[j];
first=false;
}
else
{
node[t].next=f[j];
}
t=e[j];
}
}
node[t].next=-1;
}
void Myradixsort(int elem[],int n,int r,int d)
{
list *node;
int *f,*e;
int i,p;
node=new list[n+1];
f=new int[r];
e=new int[r];
for(i=1;i<=n;i++)
{
node[i].e=elem[i-1];
node[i].next=i+1;
}
node[0].next=1;
node[n].next=-1;
for(i=1;i<=d;i++)
{
MyDistribute(node, n,r,d,i,f,e);
MyColect(node,n,r,d,i,f,e);
}
p=node[0].next;
for(i=0;i<n;i++)
{
elem[i]=node[p].e;
p=node[p].next;
}
delete []f;
delete []e;
delete []node;
}
int main(){
int *a;
int size=10;
int pos;
a=new int[size];
int b[10]={23,12,14,11,10,13,56,45,11,10};
cout<<"排序前的数列:";
for(int k=0;k<10;k++)
cout<<b[k]<<" ";
cout<<endl;
Myradixsort(b,size,10,2);
cout<<"排序后的数列:";
for(int l=0;l<10;l++)
cout<<b[l]<<" ";
cout<<endl;
delete []a;
return 0;
}