#include <iostream>
#include <string>
#include <queue>
#include <vector>
using namespace std;
typedef string *pString;
typedef queue<pString> StrBucket;
/*
变长的字符串的字典排序
输入:
strings:有字符串组成的数组,待排序
strCnt:strings中的字符串的个数
m:每个字符的范围在0-m之间
输出:
计算之后得到的strings就是排序后的字符串数组
*/
void VaryLenLexicographicSort(string * strings, int strCnt, int m = 256)
{
unsigned int maxlength = 0;
for (int i = 0; i < strCnt; i++)
{
if (maxlength<strings[i].length())
{
maxlength = strings[i].length();
}
}
//分门别类,长度一样的在一块
vector<pString> *length = new vector<pString>[maxlength + 1];
//根据这里的顺序,来找到桶里的值,this is key
vector<char> *nonempty = new vector<char>[maxlength];
for (int i = 0; i < strCnt; i++)
{
//length 编号 ==value的地址的字符串长度
//length[3]=0x38922;0x38922->"abc";
length[strings[i].length()].push_back(&strings[i]);
for (int j = 0; j < strings[i].length(); j++)
{
nonempty[j].push_back(strings[i].at(j));
}
}
//打印nonempty的
for (int i = 0; i < maxlength ;i++)
{
cout << i<< " ";
for (auto ib = nonempty[i].cbegin(); ib != nonempty[i].cend();ib++)
{
cout << *ib<<" " ;
}
cout << endl;
}
queue<pString> q,qtemp;
StrBucket *buckets = new StrBucket[m];
for (int i = maxlength-1; i >=0; i--)
{
//长度从大到小,进行操作
for (int x = 0; x < length[i + 1].size();x++)
{
cout << *length[i + 1].at(x) << endl;
q.push(length[i + 1].at(x));
}
//先处理最长的,放到桶里
while (!q.empty())
{
pString ps = q.front();
//索引值:最长的从最后一个字符开始,压入其地址
buckets[ps->at(i)].push(ps);
q.pop();
}
//nonempty[i]有序
sort(nonempty[i].begin(), nonempty[i].end());
//打印nonempty的
for (int index = 0; index < maxlength; index++)
{
cout << index << " ";
for (auto ib = nonempty[index].cbegin(); ib != nonempty[index].cend(); ib++)
{
cout << *ib << " ";
}
cout << endl;
}
//根据nonempty[i]的顺序,来找到桶里的值,this is key
for (int j = 0; j < nonempty[i].size(); j++)
{
int val = nonempty[i].at(j);
while (!buckets[val].empty())
{
pString ps = buckets[val].front();
q.push(ps);
buckets[val].pop();
}
}
qtemp = q;
while (!qtemp.empty())
{
cout << *qtemp.front() << endl;
qtemp.pop();
}
}
cout << "结果:" << endl;
while (!q.empty())
{
cout << *(q.front()) << endl;
q.pop();
}
if (length!=nullptr)
{
delete[] length;
}
if (nonempty!=nullptr)
{
delete[] nonempty;
}
if (buckets!=nullptr)
{
delete[] buckets;
}
}
void testVaryLenLexicographicSort()
{
string *strings = new string[7];
strings[0] = "abc";
strings[1] = "bac";
strings[2] = "ab";
strings[3] = "cba";
strings[4] = "ba";
strings[5] = "bbc";
strings[6] = "c";
for (int i = 0; i < 7;i++)
{
cout << strings[i].length()<<" "<<strings[i] << endl;
}
VaryLenLexicographicSort(strings, 7);
}
void main()
{
testVaryLenLexicographicSort();
cin.get();
}
不定长串的字典排序
最新推荐文章于 2025-04-15 15:27:39 发布