Radix Sort (MSD)

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

Algorithm
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:. 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.

0's: 0's: [001] 1's: [010 011] 1's: 0's: [101 100] 1's: [111 110]

Sort again with the next MSD.

0's: 0's:   1's: [001] 1's:  0's: [010] 1's: [011] 1's: 0's:   0's: [100] 1's: [101] 1's:  0's: [110] 1's: [111]

Append and convert:

[001 010 011 100 101 110 111] [1 2 3 4 5 6 7]

Sorted!

Pseudocode
#base 4 MSD sort procedure msdSort(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 msdSort(buckets[0],cur - 1) msdSort(buckets[1],cur - 1) msdSort(buckets[2],cur - 1) msdSort(buckets[3],cur - 1) arr = join(buckets) end

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