LSD基数排序c++代码



我编写了这段代码来实现字符串的lsd基数排序算法。

逻辑:我们从最低有效数字开始,首先对这个数字进行排序。然后,我们移动到左边的下一位,以此类推。count[]包含每个英文字母在特定数字位置的频率。count[1]代表'a'的频率,count[2]代表'b'的频率。等等……和count[0]=0。然后,我们计算累积计数。现在我们再次遍历字符串数组并计算aux数组中的适当位置。例如:如果count[2] = 4count[1]=1对应一个特定的数字位置,这意味着'b'在该位置的单词将占据aux[1], aux[2], aux[3]

#include<iostream>
#include<string>
using namespace std;
int main()
{
string arr[]={"dab","cab","fad","bad","dad","ebb","ace","add","fed","bed","fee","bee"};
string aux[12]={"dab","cab","fad","bad","dad","ebb","ace","add","fed","bed","fee","bee"};
int count[27]={0};
for(int i=2;i>=0;i--)
{
for(int j=0;j<12;j++)
count[static_cast<int>(arr[j][i])-64]++;
cout<<"here"<<endl;    //////////////THIS GETS PRINTED
for(int j=0;j<26;j++)
count[j+1]+=count[j]; //calculating cumulative value
cout<<"HERE"<<endl;   ///////////////THIS GETS PRINTED
for(int j=0;j<12;j++)
{
int x=count[static_cast<int>(arr[j][i])-65]; //65 because positions for 'a' will be 
                                             //determined by count[0], for 'b' will be
                                             // determined by count[1] etc.  
aux[x]=arr[j];
cout<<j<<endl;  //even j=0 doesn't get printed
count[static_cast<int>(arr[j][i])-65]++;
}
cout<<"here"<<endl;
for(int j=0;j<12;j++)
cout<<aux[j]<<endl;
} //i governs which digit is being compared
return 0;
}

代码在打印here和here后出现段错误。问题出在第三个for j循环中。谁能找出问题所在吗?

有一个小错误…我要减去65这是ascii码代表A而不是A

最新更新