用基数排序实现单词按字典序排序(包含大写)

这里写图片描述
输入字符串的处理:
因此字符串中最长单词的长度为mxp
基数排序时将每个长度小于mxp的字符串后位填补‘A’
即Cards Cap中mxp=4,Cap–>CapAA
这样全部的字符串就统一长度。ios

代码:web

#include<iostream>
#include<stdio.h>
#include<math.h>
#include<list>
#include<vector>
#include<string.h>
using namespace std;
typedef vector<string> vec_wd;
int rd=52;
int mxp;//最长单词的位数
int n;//表示有多少个单词

void sort_Dic(vec_wd src) {
// cout<<"-------------------"<<endl;
// for(int i=0; i<n; i++) {
// cout<<src.at(i)<<endl;
// }
    for(int k=1; k<=mxp; k++) { //进入每一趟基数排序
        vector<vec_wd> mat(52);//大小写各占26
        for(int j=0; j<n; j++) { //遍历每个单词
            int len=src.at(j).size();
// cout<<"len="<<len<<endl;
            if(len<mxp&&k<=(mxp-len)){//后补空位填充A
                int loc=0;
                mat[loc].push_back(src.at(j));
// cout<<"word="<<src.at(j)<<endl;
// cout<<"loc="<<loc<<endl;
            }
            else{
                int idx=mxp-k;
                int loc;
                char obj=src.at(j).at(idx);
                if(obj<='Z'&&obj>='A')
                loc=obj-'A';
                else
                loc=obj-'a'+26;
// cout<<"word="<<src.at(j)<<endl;
// cout<<"loc="<<loc<<endl;
// cout<<"mat-sz="<<mat.size()<<endl;
                mat[loc].push_back(src.at(j));
// vec_wd tmp;
// tmp.swap(mat.at(loc));
// tmp.push_back(src.at(j));
// mat.at(loc).push_back(tmp);

            }
        }
        src.clear();
for(int i=0;i<rd;i++){//把基数表中的单词放入序列

    if(!mat[i].empty()){
        int sz=mat[i].size();
        for(int j=0;j<sz;j++){
            src.push_back(mat[i].at(j));
// cout<<"src<--"<<mat[i].at(j)<<endl;
        }
    }
}

    }
// cout<<"-------------------"<<endl;
     for(int i=0; i<n; i++) {
            cout<<src.at(i)<<endl;
        }

}
int main() {
// vector<vec_wd> words(26);
// vector<string> tmp;
// tmp.push_back("cas");
// tmp.push_back("asf");
// tmp.push_back("asda");
// printf("sz_tmp=%d\n",tmp.size());
// words.push_back(tmp);
// words.push_back(tmp);
// words.push_back(tmp);
// printf("sz=%d",words.size());


    vec_wd words;

    while(cin>>n) {
        getchar();
        char str[101];
        mxp=0;
        words.clear();
        for(int j=0; j<n; j++) {
            gets(str);

            int len=strlen(str);

            if(mxp<len)
                mxp=len;
// for(int i=0; i<len; i++) { //统一转化为小写
// if(str[i]<='Z'&&str[i]>='A') {
// int g=str[i]-'0';
// g+=32;
// str[i]=g+'0';
// }
// }
            string ss=str;
            words.push_back(ss);

        }
        sort_Dic(words);


    }
    return 0;
}