Search code examples
carrayssortingcounting-sort

Counting Sort - C


So I tried to implement Counting Sort as an exercise, but there is a mistake that I'm not able to fix.

Here's the code:

#include <stdio.h>
#include <stdlib.h>

void ordenar(int vet[], int b, int k)
{
    int num[k];
    int c0=0,c1=0, n, frescura=0;

    for (n=0; n<k+1; n++)
    {
        num[n] = 0;
    }

    for(n=0;n<b+1;n++)
    {
        num[vet[n]]++;
    }

    for(n=0;n<=b;)
        {
        while(num[frescura]>0)
        {
            vet[n] = frescura;
            n++;
            num[frescura]--;
        }
        frescura++;
        }
    int y;
    for (y=0; y<b+1; y++)
    {
        printf("%d, ", vet[y]);
    }

}

main ()
{
    int a[]={8,2,3,4,1,45,12,23,1,4,5,1,9,2,4,82,0,3,0,0,0,0,23,4,8,1,1,1,1,1,1,3,2,4,
            1,3,3,3,3,4,21,4,2,4,1,4,12,4,1,4,2,4,2,95,32,32,23,41,14,0,0,1,4,24,24,2,
            2,2,2,2,2,1,3,14,14,15,5,5,6,7,8,9,0,1,2,3,4,666,4,3,2,1,9,3,4,2,1,0,51,23,12,
            23,23,14,15,16,18,81,28,18,19,20,3,1,9,9,9,2,4,1,65,2,13,13,29,93,42,6}, b, k=666;

    b = sizeof(a)/sizeof(a[0]);
    ordenar(a, b, 666);
    return 0;
}

The problem is: the code seems to put this array in order, except for the penultimate number, which is the number of elements of said array.


Solution

  • You have defined num as

    int num[k];
    

    and later are accessing elements till k

    for (n=0; n<k+1; n++) // 0 to k
    {
        num[n] = 0;
    }
    

    But, as the index of arrays starts from 0 , the array would have elements indexed from 0 to k-1

    So, the above code would result in accessing elements out of bound. Which is Undefined Behavior in C