This code takes some effort to understand even if you know how radix sort works. It's easier to first understand the abstract description of radix sort than try to reverse-engineer it from this code.
Some technical observations about the code:
- The external loop controls
exp
which goes from 1,10,100... through consecutive powers of ten and determines which decimal digit of the numbers we currently sort on. - The actual sorting into buckets is two-pass. The first inner loop computes counts for each bucket, the third spreads the numbers into respective buckets (going from n to 1 both in
a[]
and within each bucket.) - The buckets are represented as intervals in the auxilliary
b[]
array (whose offsets are precomputed in the second inner loop based on the bucket counts from the first inner loop) - After the second loop
bucket[d]
is the index of the upper end (exclusive) of the interval that will store the numbers whose active digit (the one we sort on) isd
. The bucket intervals are filled from this end downwards.