i implemented a simple count sort please find problem with it

Joined
Aug 10, 2021
Messages
1
Reaction score
0
string countSort(string arr){
int n=arr.size();
char res[n];
int count[24]={0};

for(int i=0;i<n;i++)
{
count[(int)(arr-'a')]++;
}

for(int i=1;i<n;i++)
count+=count[i-1];

for(int i=n-1;i>=0;i--)
{
res[count[(int)(arr-'a')]-1]=arr;
count[(int)(arr-'a')]--;
}

for(int i=0;i<n;i++)
{
arr=res;
}
return arr;
}
 
Joined
Mar 3, 2021
Messages
240
Reaction score
30
There's a lot to unpack here, as it doesn't compile. It's hard to tell the intent of some of it, so I can't get it working without a few wild guesses. Firstly, `arr-'a'` isn't valid, nor is `count+=count[i-1]`. I'll assume that's supposed to be `arr` and `count` throughout, as that at least compiles.

Why is count 24 elements? It appears that you're sorting lowercase letters, so you'd want 26. Ignoring that: your second loop, updating the count array is not. It should be incrementing to the end of count, not to n.
C++:
for(int i=1;i<24;i++){
    count[i]+=count[i-1];
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top