Radix sort using counting sort

3.2k views Asked by At

This radix sort algorithm is using counting sort as the stable sort required in it. This sorts correctly when given an input of 3 numbers with small number of digits but the sorting algorithm stops working for higher input values. Thanks in advance

   #include<stdio.h>
    int digits(int k)
    {
        int i=0;
        while(k!=0)
        {
            k=k/10;
            i++;
        }
        return i;
    }
    void radixsort(int a[],int size,int k)
    {
        int c[10],b[50],i,j,l,m=10,n=1;
        for(l=1;l<=k;l++)
        {
            if(l==1)
            {
                m=10;
                n=1;
            }
            else
            {
                m=m*10;
                n=n*10;
            }
            for(i=0;i<=9;i++)
            {
                c[i]=0;
            }
            for(j=1;j<=size;j++)
            {
                c[(a[j]%m)/n]=c[(a[j]%m)/n]+1;
            }
            for(i=0;i<=9;i++)
            {
                c[i]=c[i-1]+c[i];
            }
            for(j=size;j>=1;j--)
            {
                b[c[(a[j]%m)/n]]=a[j];
                c[(a[j]%m)/n]--;
            }
            for(i=1;i<=size;i++)
            {
                a[i]=b[i];
            }
        }
    }
    main()
    {
        int a[50],i,size,k=0;
        printf("enter the size of the array\n");
        scanf("%d",&size);
        printf("enter the numbers of the elements\n");
        for(i=1;i<=size;i++)
        {
            scanf("%d",&a[i]);
            if(k<a[i])
            k=a[i];
        }
        radixsort(a,size,k);
        for(i=1;i<=size;i++)
        {
            printf("%d\n",a[i]);
        }
    }
1

There are 1 answers

0
Armali On

The move part of the loop is moving from the end of array to start, this will not be stable. The digits function is never called. for(j=1; ... ) should be for(j = 0; j < size; ... The next loop is using c[i-1] when i is zero. You could use int c[11] instead of c[10], and use c[1+(a[ ...] ...] ++, then ignore c[10] when converting counts into indices (c[0] = 0, c[1] = #0's, c[2] = #0's + #1's, ...), then move from start to end (j=0; j < size; ...) . – rcgldr