排序方法9---基数排序

#include<stdio.h>
#include<iostream>
#include<malloc.h>
#define MAXE 20	    //线性表中最多元素个数
#define MAXR 10	    //基数的最大取值
typedef struct node
{
	int key;
	struct node *next;
}NodeType;
void CreateList(NodeType *&p, int a[], int n)
{
	NodeType *s, *t=NULL;
	for (int i = 0; i < n; i++)
	{
		s = (NodeType *)malloc(sizeof(NodeType));
		s->key = a[i];
		if (i == 0)
		{
			p = s; t = s;
		}
		else
		{
			t->next = s; t = s;
		}
	}
	t->next = NULL;
}
void DispLink(NodeType *p)
{
	while (p != NULL)
	{
		printf("%4d", p->key);
		p = p->next;
	}
	printf("\n");
}
void DestroyedLink(NodeType *p)
{
	NodeType *pre = p, *q = pre->next;
	while (q != NULL)
	{
		free(pre);
		pre = q;
		q = pre->next;
	}
	free(pre);
}
int keyi(int s, int i)
{
	for (int j = 0; j < i; j++)
		s = s / 10;
	return s % 10;
}
void RadixSort(NodeType *&p, int r, int d)
{
	NodeType *head[MAXR], *tail[MAXR], *t;
	int i, j, k;
	for (i = 0; i < d; i++)       //从低位到高位循环
	{
		for (j = 0; j < r; j++)       //初始化各链队首、尾指针
			head[j] = tail[j] = NULL;
		while (p != NULL)         //对于原链表中每个结点循环
		{
			k = keyi(p->key, i);       //找第k个链队
			if (head[k] == NULL)        //进行分配
			{
				head[k] = p;
				tail[k] = p;
			}
			else
			{
				tail[k]->next = p;
				tail[k] = p;
			}
			p = p->next;
		}
		p = NULL;							//重新用p来收集所有结点
		for (j = 0; j<r; j++)        		//对于每一个链队循环
			if (head[j] != NULL)         	//进行收集
			{
				if (p == NULL)
				{
					p = head[j];
					t = tail[j];
				}
				else
				{
					t->next = head[j];
					t = tail[j];
				}
			}
		t->next = NULL;       //最后一个结点的next域置NULL
		printf("按%d位排序:", i + 1); DispLink(p);
	}
}
int main()
{
	int n = 10; NodeType *p;
	int a[] = { 75,223,98,44,157,2,29,164,38,82 };
	CreateList(p, a, n);
	printf("   排序前:"); DispLink(p);
	RadixSort(p, 10, 3);
	printf("   排序后:"); DispLink(p);
	DestroyedLink(p);
	system("pause");
	return 1;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Yun_Ge/article/details/85610439