Question

I know that radix sort works by comparing the digits of the numbers. My question is, assume we have different numbers with different number of digits. Does radix sort work here? We can simply assume that, for example, if we are comparing two numbers, one with 3 digits and one with 6 digits, the first 3 digits of the smaller number is 0. But how about the implementation? How can we make the program assume that if there are not enough digits, then those digits are zero?

Thank you.

Was it helpful?

Solution

You need to somehow add or simulate those nonexistent digits or sort the numbers in groups, each of which containing only numbers of the same length.

These 3 numbers

9912
 999
 123

can be transformed into

9912
0999
0123

and sorted using the regular radix sort or they can be sorted as 2 independent groups:

9912

and

 999
 123

The latter will give you (assuming ascending order)

 123
 999

and the former stays the same. Then you combine the sorted groups (from shorter numbers to longer numbers):

 123
 999
9912

That's all.

OTHER TIPS

Assuming you have the number in an integer variable, then you can extract the digits like this (n = 0, 1, 2, ...):

digit = (number / radix ^ n) % radix
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top