字符串的比较是从高有效位开始依次比较,和长度没有太大关系。因此可以理解为末尾补零,长度相同。先将字符串按长度进行排序,然后从低有效位开始比较,对零(没有的位)不进行处理(已经在正确的位置)。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void radixSort(vector<string> & arr,int maxLen)
{
const int BUCKETS=256;
vector<vector<string>> wordsByLength(maxLen+1);
vector<vector<string>> buckets(BUCKETS);
for(auto & s:arr)
wordsByLength[s.length()].push_back(std::move(s));
int idx=0;
for(auto & wordList:wordsByLength)
for(auto & s:wordList)
arr[idx++]=std::move(s);
int startIndex=arr.size();
for(int pos=maxLen-1;pos>=0;--pos)
{
startIndex-=wordsByLength[pos+1].size();
for(int i=startIndex;i<arr.size();++i)
{
buckets[arr[i][pos]].push_back(std::move(arr[i]));
}
idx=startIndex;
for(auto & theBucket:buckets)
{
for(auto & s:theBucket)
arr[idx++]=std::move(s);
theBucket.clear();
}
}
}
int main()
{
vector<string> arr={"accde","12345","ABCDE","adc","a"};
radixSort(arr, 5);
for(auto & s:arr)
{
cout<<s<<endl;
}
}