Skip to content

Radix Sort

Not really a sorting algorithm by itself, but it's a technique that applies a stable sorting algorithm on parts of the key. In practice, it often uses counting sort because counting sort benefits when the key range is small. For instance, instead of sorting values from 1 to 10000, you can perform several passes of counting sort, each time sorting single digits. Fundamentally, it's a tradeoff between time and space.

Time Complexity

We'll assume we're using counting sort. If you use a different sorting algorithm, the time complexity will be different.

  • Time Complexity: \(O(d \cdot (n+M))\)
    • \(O(n + M)\) is the time complexity of counting sort where we are sorting \(n\) numbers ranging from \(0\) to \(M\).
    • Counting sort is used \(d\) times

Implementation

For instance, let's assume we're sorting this array: \([3214, 2213, 1254, 3253]\)

  • Sort by LSD (LSD is Least Significant Digit. That being said, I can't stop you from thinking of something else)

    • Array after one pass of counting sort on LSD: \([2213, 3253, 3214, 1254]\)
  • Sort by tens place

    • \([2213, 3214, 3253, 1254]\)

    Info

    Do note the importance of using a stable sorting algorithm. If an unstable sorting algorithm is used, we might get this after sorting by tens place:

    \([3214, 2213, 1254, 3253]\)

  • Keep sorting by next place until you finish sorting

    • \([2213, 3214, 3253, 1254]\)
    • \([1254, 2213, 3214, 3253]\)

Time Complexity Analysis

We used counting sort 4 times (d=4). Also, the range of numbers for each application of counting sort is 0 to 9 (10 numbers in total). To sort \(n\) 4-digit numbers, the time complexity will be:

\[ O(4 imes (n + 10)) = O(n) \]

Q&A

Can I sort 2 digits at a time?

Sure, just note the tradeoffs. If you call counting sort twice, then each time the range of numbers will be 0 to 99 (100 numbers in total).

The time complexity will be:

\[ O(2 imes (n + 100)) = O(n) \]

It'll still be \(O(n)\) with differing constants.

Counting sort will use more memory because Instead of an array of 10 numbers, you'll need an array of size 100. However, the algorithm runs faster because the sorting function is called lesser number of times.

Can I use other stable sorting algorithms

Sure, but the time complexity will be different.

Can I sort from the MSB instead?

Sure, you can do anything.