Sorter coder

Sorting Algorithms: Radix Sort

tags : algorithms,sorting,divide-and-conquer, level: ha, medium

utilize existing
algorithm
keypoints
does NOT use
comparisons
sort on individual digits
counting sort
complexity
time complexity
O(n)
space complexity
O(n) ?

radix sort image


Sort elements based on value of a single digits in each pass.


Radix ( or base ) is the number of digits used to represent a number, for e.g. decimal system uses 10 digits (0..9)(0..9), binary uses 2 digits (0,1)(0,1).

Radix sort does NOT use comaprison for sorting, hence it can be faster than comparison sorts which are speed limited to O(nlog(n))O(n log(n)) on the speed.
It can run as fast as O(n+k)O(n+k) time.
It can be used to sort strings when they are represented as integers.


General idea

Pass over the array once for each digit.
In each pass use stableSort to sort the array based on only one digit.

radixSort (array):
    for digit -> 0 to numberOfDigits:
        stableSort(array, digit)

radix sort general idea


LSD sort : Least Significant Digit

  • Each number should have the same number of digits (width).

radix sort lsd

lsdRadixSort(array):
    for lsd -> digits to 0: //lsd -> msd
        countingSort(array, lsd)
countinsSort(array, digit):
  //TODO

MSD sort : Most significant Digit

radix sort image

MSDsort(array, 0, array.length, 0)

MSDsort(array, subArrStart, subArrEnd, msd):
  count = countingSort(array, msd)
  for i->0 to maxWidth //radix
     MSDsort(array, count[i], count[i+1], i+1)

Running time

Best case

MSD radix : Points to note

  • Large number of small subarrays
  • When all the strings/number are the same
  • Counting sort uses extra space since it uses a count array and an aux array, this can be eliminated if we sacrifice stability

In Books

  • Algorithms, 4th Edition, Sedgewick, Chapter 5.1, "MSD String Sort"

References

Brilliant Radix Sort MIT OCW lecture notes