基数排序之定长字典排序

#include <iostream>
#include <queue>


using namespace std;

typedef int * pInt;
typedef queue<pInt> Bucket;

/*
	定长的字典排序
	输入:
		A:待排序的整数序列的数组。每个元素是一个整数序列,按照这些整数字典排序
		n:整数序列的个数
		k:整数序列的长度
		m:整数序列中的每个整数范围从0到m-1
	输出:A是已经排序好的整数序列。
*/
void LexicographicSort(pInt *A, int n, int k, int m)
{
	Bucket *buckets = new Bucket[m];
	queue<pInt> q;
	for (int i = 0; i < n; i++)
	{
		q.push(A[i]);
	}
	//为什么要从后往前遍历,因为从后往前遍历,在当前数值相等的情况下,保证后面的数值是有序的。
	for (int i = n-1; i >=0; i--)
	{
		while (!q.empty())
		{
			pInt a = q.front();
			q.pop();
			buckets[a[i]].push(a);

		}
		for (int l = 0; l < m; l++)
		{
			while (!buckets[l].empty())
			{
				q.push(buckets[l].front());
				buckets[l].pop();
			}
		}
		//打印排序一遍的队列
		queue<pInt> qTemp(q);
		while (!qTemp.empty())
		{
			for (int i = 0; i < k; i++)
			{
				cout << qTemp.front()[i] << '\t';
			}
			cout << endl;
			qTemp.pop();
		}
		cout << "--------------------------------" << endl;

	}
	if (buckets!=nullptr)
	{
		delete[] buckets;
	}
	while (!q.empty())
	{
		for (int i = 0; i < k;i++)
		{
			cout << q.front()[i] << '\t';
		}
		cout << endl;
		q.pop();
	}

}
void testLexicographicSort()
{
	pInt*a = new pInt[5];
	int a1[] = { 1, 2, 3, 5, 6 };
	a[0] = a1;
	int a2[] = { 2, 3, 6, 9, 2 };
	a[1] = a2;
	int a3[] = { 1, 3, 5, 4, 3 };
	a[2] = a3;
	int a4[] = { 2, 3, 4, 5, 6 };
	a[3] = a4;
	int a5[] = { 1, 3, 4, 8, 4 };
	a[4] = a5;
	LexicographicSort(a, 5, 5, 10);
}
void main()
{

	
	testLexicographicSort();

	cin.get();
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值