Search code examples
algorithmsortingradix-sort

Does radix sort work with numbers who have different number of digits?


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.


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.