This algorithm was first used in old punched card sorting machines. The keys must be integers of some standard length or keys that can be mapped to this. This is reasonably easy to implement in hardware, but more difficult to do in software without creating so many data swaps that the time become prohibitive bog down.
/***************************************/ /* RadixSort() */ /* */ /* Sort records on integer key using */ /* a radix sort. */ /* Note: This sort is made faster by */ /* using two arrays of pointers to */ /* structs. The structures are then */ /* sorted by moving the pointers */ /* instead of the structures themselves*/ /* This speeds up the sort because it */ /* is much quicker to move a 4-byte */ /* pointer than it is a large struct. */ /***************************************/ void RadixSort(StructType DataArray[], StructType DataArray2[], int count) { int i, j, k, radixN, radixNplus1, index; StructType *temp1[ARRAYMAX], *temp2[ARRAYMAX]; StructType **arrayIn, **arrayOut, **arrayTemp; /* Create initial array of pointers to structs */ for(i=0; i<count; i++) temp1[i] = &DataArray[i]; /* Set initial pointers to arrays of pointers */ arrayOut = &temp1[0]; arrayIn = &temp2[0]; for(i=0; i<(int)ceil(log10(MAXKEY)); i++) /* Get # digits in the key, i.e. ceil(log10(9999)) = 4 */ { index = 0; /* Start at beginning of arrays of pointers */ radixN = (int)ceil(pow(RADIX, i)); radixNplus1 = (int)(radixN * RADIX); for(j=0; j<RADIX; j++) /* Sort into 10 stacks */ { for(k=0; k<count; k++) /* Look at all records */ { /* To isolate one digit: (num % radixi+1 ) / radixi */ if( ( (int)floor(((*(arrayOut+k))->key % radixNplus1) / radixN)) == j) { /* Copy the pointer */ *(arrayIn+index) = *(arrayOut + k); index++; } } } /* Swap the array pointers */ arrayTemp = arrayOut; arrayOut = arrayIn; arrayIn = arrayTemp; } /* Copy structs from Array1 in sorted order into Array2 */ /* Use arrayOut here as it was the result of the last */ /* sorting after the pointers were swapped. */ for(i=0; i<count; i++) DataArray2[i] = *(*(arrayOut + i)); }