#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();
}
基数排序之定长字典排序
最新推荐文章于 2022-06-10 17:03:21 发布