看数据结构写代码(65) 基数排序

欢迎指出代码不足

参考书本:严蔚敏《数据结构 .C语言版》

// RadixSort.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#define MAX_SIZE 1000//最大空间
#define RADIX	 10//关键字基数
#define KEY_NUM 3//关键字个数

struct SLNode{//静态链表节点
	int key;
	int next;
};

struct SLList{//静态链表
	SLNode base[MAX_SIZE];
	int keyNum;//关键字数量
	int len;
};

typedef int Arrtype [RADIX];//指针数组

void initList(SLList * list,int * array,int num){
	for (int i = 0; i < num; i++){
		list->base[i].next = i + 1;
		list->base[i+1].key = array[i];
	}
	list->base[num].next = 0;
	list->len = num;
	list->keyNum = 3;
}

int ord(int key,int i){//获取地址 (0~9 )
	if (i == 0){
		return key % 10;
	}
	else if(i == 1){
		return key % 100 / 10;
	}
	else{
		return key / 100;
	}
}

//分配函数
//i : 关键字 次数
//f: 队头指针数组
//e:队尾指针数组
void distribute(SLList * list,int i,Arrtype * f,Arrtype * e){
	for (int j = 0; j < RADIX; j++) (*f)[j] = 0;//清空队头数据
	int next = list->base[0].next;
	for (; next != 0; next = list->base[next].next){
		int index = ord(list->base[next].key,i);
		if ((*f)[index] == 0){
			(*f)[index] = next;
		}
		else{
			list->base[(*e)[index]].next = next;
		}
		(*e)[index] = next;
	}
	printf("\n");

}

int getNext(Arrtype f,int i){
	for ( ; i < RADIX; i++) {
		if (f[i] != 0){
			return i;
		}
	}
	return -1;
}

//收集函数(分配函数 已经 将 需要排序的 数组 分块了,现在 需要 将这些 块 链接起来)
void collect(SLList * list,Arrtype f,Arrtype e){
	int first = getNext(f,0);
	if (first != -1){
		list->base[0].next = f[first];//设置 头指针的后继
		int next = getNext(f,first+1);
		int pre = first;
		for (; next != -1; ){
			list->base[e[pre]].next = f[next];
			pre = next;
			next = getNext(f,next+1);
		}
		list->base[e[pre]].next = 0;//设置最后节点的后继 为 0
	}

}

void printList(SLList list){
	printf("------------------打印静态链表--------------------\n");
	int next = list.base[0].next;
	while (next != 0){
		SLNode nextNode = list.base[next];
		printf("%d\t",nextNode.key);
		next = nextNode.next;
	}
	printf("\n");
}

void radixSort(SLList * list){
	Arrtype f;
	Arrtype e;
	for (int i = 0; i < list->keyNum; i++){
		distribute(list,i,&f,&e);//分配,时间复杂度 O(n),n为 排序数组的大小
		collect(list,f,e);//收集...
		printList(*list);
	}
}



static int testArray[] = {656,301,305,998,999,875,832,423,432,565};

int _tmain(int argc, _TCHAR* argv[])
{
	SLList list;
	initList(&list,testArray,10);
	radixSort(&list);
	return 0;
}
运行截图:

打印了 3次 静态链表,分别 是 对 “个位”,“十位”,“百位” 分配,收集之后 静态链表的情况。



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值