Feb 12, 2011

Radix Sort: C Implementation

Radix sort is one of the most popular algorithms and is used to sort the integers. It is based on counting sort and that makes it different from other algorithms which are based on comparison sorting. It gets name Radix sort because radix means digit. In this, stable counting sort runs on each radix position to sort the integers.
E.g.
I = {10,123,39,9,1234,56} and radix = 10
For I, first we run count sort on unit digit position and the output will be
I0 = {10,123,1234,56,39,9}
Then count sort is run on 10th position of I0 and output will be
I1 = {9,10,123,1234,39,56}
Please note that upto 2nd digit, whole array is sorted.
Similarly, for 100th position
I2 = {9,10,39,56,123,1234}
For 1000th position
I3 = {9,10,39,56,123,1234}
And I3 is sorted.
It is done by using Radix 10. Count sort employed here must be stable. Otherwise, whole array may not be sorted.
To extract ith digit from x use
x*RADIX/(RADIX^i)%RADIX

C Implementation:

#define SIZE 256
#define RADIX 10 //We are using 10 as base
void countsort(int *x,int n,int range,int *o,int digitposition)
{
int temp[RADIX];
int i;

for(i=0;i
    temp[i] = 0;
for(i=0;i
    temp[(x[i]*RADIX/digitposition%RADIX)]+=1;

for(i=1;i
    temp[i] += temp[i-1];

for(i=n-1;i>=0;i--)
    o[temp[(x[i]*RADIX/digitposition%RADIX)]-- -1] = x[i];
}

void radixsort(int *x,int n,int *xo)
{
int i,digex,j,digitcount;
int max=x[0];

for(i=1;i
    {
    if(x[i]>max)
        max = x[i];
    }
digitcount = 0;

//To count the number of digits
while(max)
    digitcount++,(max/=RADIX);

//Starting digit that is at unit place
digex = RADIX;
for(j=1;j<=digitcount;j++)
    {
    countsort(x,n,RADIX,xo,digex);
    for(i=0;i
        {x[i] = xo[i];//Copy the output to make it input for next iteration

        }
    digex *= RADIX;
    }
}

int main()
{
int x[SIZE],ox[SIZE];
int n;
int i;
scanf("%d",&n);
for(i=0;i
    scanf("%d",&x[i]);
radixsort(x,n,ox);
for(i=0;i
    printf("%d\n",ox[i]);
return 0;
}


Time Complexity: O(n*d) where n is the size of input and d is the number of digit
Space Complexity: O(n+RADIX)
Please feel free to comment if you find anything wrong. 

1 comment:

  1. Please note that above implementation is for non negative integers only.
    For negative integers, soon it will updated.

    ReplyDelete