Skip to content

Radix Sort

OperationMethodTimeAdaptive?In-Place?Stable?Online?
Radix sortNon-ComparisonΘ(d(n+k))********

Idea

The main idea is to sort n elements with d figures, which range 0k , where:

  • 1 is the less significant figure(rightmost), the one we start with.
  • d is the most significant figure (leftmost)

The result is sorting by starting from the rightmost figure to the leftmost one.

Radix Sort ex

The Algorithm

python
radixsort(array A, int d)
    for (i = 1 to d):
        sort(A, i) #Use a stable sorting algorithm on the i-th figure
radixsort(array A, int d)
    for (i = 1 to d):
        sort(A, i) #Use a stable sorting algorithm on the i-th figure

Correctness Demonstration

Demonstration by induction on the target column to sort

  1. Base Case: i=1, we sort the only column
  2. Inductive Hypothesis: We assume the figures of the columns 1i1 are sorted
  3. Inductive Step: We demonstrate that a stable algorithm on the i-th column, keeps the columns 1,2k sorted
    1. If two figures in position i are equal, by the principle of stability, they remain in the same order as they were given. Plus, by Inductive Hypothesis they are sorted.
    2. If two figures in position i are not equal, the algorithm sorts them on the i-th column and puts them in the right position.

Lemma

Given n numbers of d figures, where each figure can have k possible values, the procedure correctly sorts them in time Θ(d(n+k)). If the sorting algorithm used is stable, the procedure takes Θ(n+k)

Time Complexity Demonstration

For each iteration the cost is Θ(n+k), which means that given d iterations we have Θ(d(n+k))

Final Time Complexity: T(n)=Θ(d(n+k))

  • sort() is a stable sorting algorithm to order the array, based on i
    • In this case T(n)=Θ(n+k)
  • If k=O(n), T(n)=Θ(dn)
  • If k=O(n) and d=O(1), T(n)=Θ(n)

Space Complexity Demonstration - Not In-Place

Let us suppose to have n integers of b bits, such that x,x[02b1]

We can divide every integer in br figures c of exactly r bits, c[02r1]

The time of execution of the radix sort is Θ(d(n+k))=Θ(br(n+2r)), then k=2r

Given the values of n and b, we choose the value of r such that rb, to minimize the function br(n+2r)

Case 1 - b<log(n)

Then, for every value of rb

n+2r=Θ(n)rb2r2b<n

In this case we choose r=b and we get:

T(n)=bb(n+2b)=Θ(n)

Case 2 - blog(n)

Then,

  • b/rnr must be large
  • b/r2rr must be small, else it would be dominant on n

The best choice is 2r=nr=log(n) and we get:

T(n)=blog(n)(n+2log(n))=Θ(bnlog(n))

Conclusions

In general we use the radix sort when the input is made of integers in the interval [0nc] where c is constant