(6)基数排序

一切细节尽在代码中

#include <iostream>
using namespace std;
#define MAX_NUM_OF_KEY 8 //关键字的个数。以3为例
#define RADIX 10 //关键字的基数,某个关键字可供选择的项
#define MAX_SPACE 1000
typedef struct {
	int keys[MAX_NUM_OF_KEY];//3个有效 
	int otheritems;//data域 
	int next;//下个元素位置 
}SLCell;
typedef struct {
	SLCell r[MAX_SPACE];
	int keynum;//起效的关键字个数
	int recnum;//链表长度,元素数量 
}SLList;

void Distribute(SLCell r[],int i,int f[],int e[]){
	cout <<"分配:"; 
	for(int j=0;j<RADIX;++j) f[j] = 0;
	int t;
	for(int p = r[0].next;p;p=r[p].next){
		//j = ord(r[p].keys[i]);
		t = r[p].keys[i];//keys[0]存个位,keys[1]存十位,keys[2]存百位 
		if(!f[t]) f[t] = p;
		else r[e[t]].next = p;
		e[t] = p;
	}
	for(int a=0;a<=9;a++){
		cout <<a<<":";
		int b = f[a];
		while(b != 0 ){
			SLCell cell = r[b];
			cout <<cell.otheritems<<",";
			if(b == e[a]) break;
			b = cell.next; 
		}
	}
	cout <<endl<<"f:";
	for(int s=0;s<=9;s++){
		cout <<f[s]<<","; 
	} 
	cout <<endl<<"e:";
	for(int s=0;s<=9;s++){
		cout <<e[s]<<","; 
	} 
	cout <<endl;
}
int succ(int o ,int f[]){
	while(o<9){
		o++;
		if(f[o]) return o;
	}
	return 10;
}
void Collect(SLCell r[],int i,int f[],int e[]){
	cout <<"收集:"; 
	for(int j=0;!f[j];j = succ(j,f));
	r[0].next = f[j];
	int t = e[j];
	while (j < RADIX) {
		for(j=succ(j,f);j<RADIX-1 && !f[j];j = succ(j,f));
		if(j != 10 && f[j]){
			r[t].next = f[j];
			t = e[j];
		}
	}
	r[t].next = 0;
	SLCell cell = r[0]; 
	for(int w = 1;w<=10;w++){
		cell = r[cell.next];
		cout <<cell.otheritems<<","; 
	}
	cout <<endl;
}
void RadixSort(SLList &L){
	for(int i = 0;i<L.recnum;i++) L.r[i].next = i+1;
	L.r[L.recnum].next = 0;
	int f[RADIX];
	int e[RADIX];
	for(i = 0;i<L.keynum;i++){
		Distribute(L.r,i,f,e);
		Collect(L.r,i,f,e);
	}
}
void print(SLList L){
	SLCell cell = L.r[0];
	for(int i = 1;i<=10;i++){
		cell = L.r[cell.next];
		cout <<cell.otheritems<<","; 
	}
	cout <<endl;
}
int main(){
	SLList L ;
	L.keynum = 3;
	L.recnum = 10;
	int arr[] = {0,278,109,63,930,589,184,505,269,8,83};
	for(int i = 1;i<=10;i++){
		L.r[i].otheritems = arr[i];
		L.r[i].keys[0] = arr[i]%10;
		L.r[i].keys[1] = arr[i]%100;
		L.r[i].keys[1] = L.r[i].keys[1]/10;
		L.r[i].keys[2] = arr[i]/100;
	} 
	for(int i = 0;i<L.recnum;i++) L.r[i].next = i+1;
	L.r[L.recnum].next = 0;
	print(L);
	RadixSort(L);
	print(L);
	return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值