Radix Sort (MSD)

MSD (Most 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 (like LSD radix sort). 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 Most Significant Digit, and recursively sort the buckets. =Example= Take a list: {7 6 1 5 4 2 3}.

We will be choosing 2 as b for now.

represent all numbers as base-2.

{111 110 001 101 100 010 011}.

Arrange them based on their MSD.

0's: {001 010 011}, 1's: {111 110 101 100}

sort the 0's and 1's bucket based on the next MSD.

{{001} {010 011}} {{101 100} {111 110}}

Sort again with the next MSD.

{{001} {{010} {011}} } { {{100} {101}} {{110} {111}} }

Append...

{001 010 011 100 101 110 111}

convert...

{1 2 3 4 5 6 7}

Sorted! =Pseudocode= #base 4 MSD sort procedure smsd(array arr,int cur) do if length(arr) <= 1 or cur < 0 do return arr end if array buckets = ],[],[],[ for j = 0 to length(arr) - 1 do buckets[i'th LSD of arr[j] in base 4].push(arr[j]) end for smsd(buckets[0],cur - 1) smsd(buckets[1],cur - 1) smsd(buckets[2],cur - 1) smsd(buckets[3],cur - 1) arr = join(buckets) end

procedure radix_sort_msd(array arr) do int len = length(ToBase4String(max(arr))) smsd(arr,len) end