-4
我寫了這段代碼來實現字符串的lsd基數排序算法。LSD基數排序C++代碼
邏輯: 我們從最低有效位數開始,並首先對這個數字進行排序。然後,我們移動到左邊的下一個數字,依此類推。 count[]
包含每個英文字母在特定數字位置的頻率。 count[1]
代表頻率'a'
,count[2]
的'b'
......等等......和count[0]=0
。然後,我們計算累計計數。現在我們再次遍歷字符串數組並計算aux
數組中的適當位置。例如:如果count[2] = 4
和count[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'循環中。任何人都可以找出問題嗎?
請修復縮進... – hyde