Question

I wrote this code to implement lsd radix sort algorithm for strings.

Logic: We start from the least significant digit and first apply sorting to this digit. Then, we move to the next digit to the left and so on. count[] contains frequency of each english alphabet at a particular digit position. count[1] represents frequency of 'a', count[2] of 'b'...so on... and count[0]=0. Then, we calculate the cumulative count. Now we again iterate through the array of strings and calculate the appropriate position in the aux array. for ex: if count[2] = 4 and count[1]=1 for a particular digit position, it means that words with 'b' at that position will occupy 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;
}

The code gives segfault after printing here and HERE. The problem is in the third 'for j' loop. Can anybody please identify the problem?

Was it helpful?

Solution

There was a minor mistake... I was subtracting 65 which is ascii for 'A' and not 'a'

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top