Pseudo Code
Lesson 4 of 9 in Coddy's Radix Sort - DSA Series course.
countingSortByDigit(array, exp):
n = length(array)
output = array of size n
count = array of 10 zeros
for each x in array: # tally each digit
count[(x / exp) % 10] += 1
for d from 1 to 9: # running totals -> positions
count[d] += count[d - 1]
for k from n-1 down to 0: # place from the back (stable)
d = (array[k] / exp) % 10
count[d] -= 1
output[count[d]] = array[k]
return output
radixSort(array):
max = largest value in array
exp = 1
while max / exp > 0:
array = countingSortByDigit(array, exp)
exp = exp * 10- exp is the place value: 1 for ones, 10 for tens, 100 for hundreds.
(x / exp) % 10pulls out that digit. - countingSortByDigit is a stable sort on a single digit: it counts how many of each digit appear, turns those counts into positions, then places elements from back to front to preserve order.
- radixSort just runs that pass once per digit, stopping when
exppasses the largest number.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Radix Sort - DSA Series
2The Algorithm
How it works?Pseudo CodeImplementation (Part 1)Implementation (Part 2)