Radix Sort (LSD)

LSD Radix Sort is a sorting algorithm that operates in $$O(n \log m)$$, where m is the max element. It also uses $$O(n)$$ memory.

= 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 2 13 6 5 12 3 10 11 15 4 9 14 8}.

We will be choosing 2 as b for now.

represent all numbers as base-2.

{0111 0010 1101 0110 0101 1100 0011 1010 1011 1111 0100 1001 1110 1000}.

Arrange them based on their LSD. the elements must be in the same relative order.

0's bucket: {0010 0110 1100 1010 0100 1110 1000}

1's bucket: {0111 1101 0101 0011 1011 0001 1111 1001}

Append.

{0010 0110 1100 1010 0100 1110 1000 0111 1101 0101 0011 1011 1111 1001}

Repeat with their next least significant digit.

0's bucket: {1100 0100 1000 1101 0101 1001}

1's bucket: {0010 0110 1010 1110 0111 0011 1011 1111}

{1100 0100 1000 1101 0101 1001 0010 0110 1010 1110 0111 0011 1011 1111}

Repeat again, with their next LSD.

0's bucket: {1000 1001 0010 1010 0011 1011}

1's bucket: {1100 0100 1101 0101 0110 1110 0111 1111}

{1000 1001 0010 1010 0011 1011 1100 0100 1101 0101 0110 1110 0111 1111}

Repeat 1 last time with their most significant digit

0's bucket: {0010 0011 0100 0101 0110 0111}

1's bucket: {1000 1001 1010 1011 1100 1101 1110 1111}

{0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111}

convert back...

{2 3 4 5 6 7 8 9 10 11 12 13 14 15}

Sorted!

= Pseudocode = #base 4 LSD sort procedure getNum(int n,int i) do string str = ToBase4String(n) int end = length(str) - 1 char digit = str[end - i]   if char == undefined do return 0 end if return toNumber(char) end procedure radix_sort_lsd(array arr) do int max = 0 for i = 0 to length(arr) - 1 do if arr[i] > arr[max] do max = i      end if end for int maxLen = ToBase4String(arr[max]) for i = 0 to maxLen do array buckets = ],[],[],[ for j = 0 to length(arr) - 1 do buckets[getNum(arr[j],i)].push(arr[j]) end for arr = join(buckets) end for end