基数排序之定长字典排序

来源:互联网 发布:华为武汉研究所光网络 编辑:程序博客网 时间:2024/06/10 15:04
#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
原创粉丝点击