CodeBlanks Logo Icon CodeBlanks

Radix idea

Sort numbers digit by digit.

Radix idea

Radix sort sorts numbers digit by digit. First by the units digit, then tens, then hundreds... Each pass uses a stable sub-sorter (usually counting sort).

We start from the least significant digit (LSD) and move toward the most significant. Stability ensures the order from earlier passes is preserved.

With d digits and base k, the cost is O(d(n + k)). Effective even for large numbers.

LSD and MSD

LSD radix sort starts from the least significant digit. It re-sorts the whole array at each digit. Because it is stable, the final order is correct.

MSD radix sort starts from the most significant digit and splits each group recursively. It is more complex but may do fewer passes in some cases.

LSD is easier to implement and usually preferred.

Practice Get digit

Write get_digit(n, d). Return digit d (0=units) of n. Print 3 with print(get_digit(738, 1)).

Starter code

solution.py
def get_digit(n, d):
    # Return digit d

Sample solution

solution.py
def get_digit(n, d):
    # Return digit d
    return n // (10 ** d) % 10
print(get_digit(738, 1))

Expected output

3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which sub-sorter does radix sort use?

  • Quick sort
  • Stable counting sort Correct answer
  • Heap sort
  • Selection sort

Explanation: Stable counting sort

2 Digit count

Question
d = len(str(____))
Answer
d = len(str(max(arr)))

Explanation: max(arr) is right.

3 Radix idea: match the terms

Term Meaning
LSD Units first
MSD Hundreds first
Sub-sorter Counting sort
Cost O(d(n+k))

All lessons in Intermediate