Radix Sort (LSD)

LSD (Least Significant Digit) Radix Sort is a distributive sorting algorithm that operates in $$O(n \log m)$$, where m is the max element. Unlike other sorting algorithms, this algorithm doesn't use comparisons, and it only works on integers. It also uses $$O(n)$$ memory, is stable, and not adaptive.

= Explanation = First, pick a base b. second, represent all numbers to be sorted in base-b. Then rearrange them into buckets based on their Least Significant Digit, and repeat the length of the longest number's representation in base-b times.

= Example = Take a list: {7 6 1 5 4 2 3}. For this example we represent the numbers in base 2:

{111 110 001 101 100 010 011}

Start by sorting numbers stably based on their least significant digit:

{11 1  11 0  00 1  10 1  10 0  01 0  01 1 }

{11 0  10 0  01 0  11 1  00 1  10 1  01 1 }

Iterate up each digit up to the MSD:

{1 1 0 1 0 0 0 1 0 1 1 1 0 0 1 1 0 1 0 1 1}

{1 0 0 0 0 1 1 0 1 1 1 0 0 1 0 1 1 1 0 1 1}

{ 1 00  0 01  1 01  1 10  0 10  1 11  0 11}

{ 0 01  0 10  0 11  1 00  1 01  1 10  1 11}

convert back to base 10 and the list is sorted:

{1 2 3 4 5 6 7}

= Pseudocode = #base b LSD sort procedure radix_sort_lsd(array arr, int b) do for i = 0 to key length of max(arr) in base b do array buckets = [][b] for each n in arr do buckets[ith digit of n in base b].push(n) end for arr = join(buckets) end for end