0

I am trying to implement a counting sort function for Pset3 find (more comfortable), and have written up the code below:

void csort(int values[], int n)
{
    int limit = 5; // CHANGE LIMIT HERE
    int counts[limit];
    for(int i = 0; i < n; i++)
    {
        counts[values[i]-1]++;
    }
    int nindex = 0;
    for(int k = 0; k < limit; k++)
    {
        for(int j = 0; j < counts[k]; j++)
        {
            values[nindex] = k;
            nindex++;
        }
    }
}

This is returning a "Segmentation fault" error, which upon a quick Google search seemed to indicate memory issues (some kind of infinite loop?) Does anyone have any idea what might be causing this and what the best approach to remedying the problem might be? Thanks!

1 Answer 1

1

This would work if no element of the values array is greater than 5. Since counts is initialized to limit, it has 5 elements, indexes 0 through 4. What happens here counts[values[i]-1]++; if values[i] is 6? It is trying to access counts[5], which doesn't exist (a memory violation).

You need to revisit the logic after int nindex = 0. For one thing, there is no test to see if counts[x] has a non-zero value. There should not be a loop here for(int j = 0; j < counts[k]; j++), but you do need a conditional (if). Suggest you rewatch the walkthrough and write psuedocode to get yourself on track.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .