-4

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

逻辑:我们从最低有效位开始,首先对这个数字进行排序。然后,我们移动到左边的下一个数字,依此类推。count[]包含每个英文字母在特定数字位置的频率。count[1]表示'a', count[2]of ...的频率'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;
}

代码在此处和此处打印后会出现段错误。问题出在第三个“for j”循环中。任何人都可以找出问题吗?

4

1 回答 1

0

有一个小错误......我减去了 65,它是 'A' 而不是 'a' 的 ascii

于 2012-12-30T18:28:49.080 回答