Which base should I use in radix sort? And how do I convert between bases?

806 Views Asked by At

If I have to sort a list of integers of base 10, firstly I convert this integers to, for example, base 2, then perform radix sort and finally convert integers back to base 10?

Generally, how do you perform radix sort with radix different from base of integers in list?

1

There are 1 best solutions below

0
On

Generally speaking, this depends on how the inputs are represented.

If your inputs are represented as fixed-width integer values, then it's easy to convert between bases by using division and mod. For example, you can get the last base-b digit of a number n by computing n % b and can drop that digit off by computing n / b (rounding down).

If your inputs are represented as strings, then it's harder to reinterpret the characters in other bases. Without using fancy algorithmic techniques, you can usually switch to bases that are powers of the base in which the number is represented by treating blocks of digits as individual digits. You can also use smaller bases by, for example, taking each digit, individually rewriting those digits in smaller bases, then using a radix sort that goes less than one digit at a time.

If you're interested in using a really heavyweight theoretical technique, this paper demonstrates a way to encode numbers in any base in binary in a way that allows for constant-time random access of the digits with no loss in space. This is certainly way more advanced than other approaches and the constant factor probably would make this inefficient in practice, but it shows that in theory it's possible to use any base you'd like.