- 2072 Asoj · 5 marks
Radix sort definition and algorithm
Short answer
Radix sort is a non-comparison sort that sorts integers digit by digit, LSD first. It distributes numbers into 10 queues based on the current digit, then collects them in queue order. Repeating for all digits yields a sorted list. Time complexity O(d·n), extra space O(n), stable.
Define a radix sort with its algorithm.
Radix sort is a non-comparison sorting method that sorts keys digit by digit, starting from the least significant digit (LSD) and moving to the most significant digit. For each digit position the keys are distributed into 10 queues (pockets), numbered 0 to 9, and then collected back in queue order. Because each pass is stable, after the last pass the list is sorted.
Algorithm
- Find the largest key and count its digits, d.
- For pass = 1 to d (units, tens, hundreds, ...):
- Take each key from the list in order and insert it at the rear of queue[digit], where digit is the current digit of the key.
- Delete all keys from queue 0, then queue 1, ... up to queue 9 (front to rear) and place them back in the list.
- After d passes the list is sorted.
void radixSort(int a[], int n) {
int max = a[0], exp, i, j, k;
for (i = 1; i < n; i++) if (a[i] > max) max = a[i];
for (exp = 1; max / exp > 0; exp *= 10) {
int q[10][100], cnt[10] = {0}; /* 10 queues */
for (i = 0; i < n; i++) { /* distribute */
int d = (a[i] / exp) % 10;
q[d][cnt[d]++] = a[i];
}
k = 0;
for (j = 0; j < 10; j++) /* collect */
for (i = 0; i < cnt[j]; i++) a[k++] = q[j][i];
}
}
Complexity: each pass takes O(n) and there are d passes, so time is O(d·n) (O(n) when d is fixed). Extra space is O(n) for the queues. It is stable and needs no key comparisons.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Radix sort on 345, 654, 924, ... · Data Structure and Algorithm, chapter 7
- Merge and radix sort on 142, 523, ... · Data Structure and Algorithm, chapter 7
- Radix sort on 32, 45, 60, 83, ... · Data Structure and Algorithm, chapter 7
- Radix sort on 25, 57, 48, 37, ... · Data Structure and Algorithm, chapter 7
- Algorithm for an exchange sort · Data Structure and Algorithm, chapter 7 · asked 2×
- Merge sort algorithm and trace · Data Structure and Algorithm, chapter 7