Radix Sorting in Data Structure
Radix sort is a non-comparison sorting algorithm that sorts integers or fixed-length strings digit by digit or character by character, from least significant to most significant (LSD) or vice versa, using a stable subroutine like counting sort.
Theory & Explanation
Radix Sort: Definition, Stepwise Working, Complexity & Code
1. Definition & Key Characteristics
Radix Sort is a non-comparison-based sorting algorithm that sorts numbers (or fixed-length keys) by processing individual digits or characters one place at a time, typically starting from the Least Significant Digit (LSD) (ones place) to the Most Significant Digit (MSD) (highest place), using a stable sorting subroutine—most commonly Counting Sort—at each digit position.
- Non-Comparison Sorting: Avoids direct element-to-element key comparisons; instead, it groups and orders elements by digit values (
0to9for decimal numbers). - Requires a Stable Subroutine: Each digit pass must preserve the relative order of elements that have the same digit at the current place; otherwise, earlier digit ordering is lost.
- Linear-Time Potential for Bounded Digits: Runs in
O(d · (n + b))time, wherenis the number of elements,dis the number of digits in the maximum element, andbis the radix/base (e.g.,b = 10for base-10 integers). - Not In-Place: Needs extra auxiliary space for count arrays and temporary output arrays during each pass.
2. How Radix Sort Works (LSD Step-by-Step Algorithm)
- Find Maximum Element: Scan the array to find
maxValso we know how many digit positionsdexist. - Loop Over Digit Places: Set place value
exp = 1(ones place). WhilemaxVal / exp > 0:- Perform a stable Counting Sort on the array based on the current digit:
digit = (arr[i] / exp) % 10. - Multiply
expby10(exp = exp 10) to move to tens, hundreds, and higher places.
- Perform a stable Counting Sort on the array based on the current digit:
- Completion: Once all digit places up to the most significant digit of
maxValhave been stably sorted, the entire array is sorted in ascending order.
3. Step-by-Step Example & Graphical Representation
Sort arr = [170, 45, 75, 90, 802, 24, 2, 66] (n = 8, maxVal = 802 → 3 passes: exp = 1, 10, 100) in ascending order:
- Pass 1 (
exp = 1, Ones Digit): Digits are0, 5, 5, 0, 2, 4, 2, 6. Stable grouping by ones digit gives:[170, 90, 802, 2, 24, 45, 75, 66]. - Pass 2 (
exp = 10, Tens Digit — leading zero for2): Tens digits are7, 9, 0, 0, 2, 4, 7, 6. Stable grouping by tens digit gives:[802, 2, 24, 45, 66, 170, 75, 90]. - Pass 3 (
exp = 100, Hundreds Digit — leading zeros for 2-digit & 1-digit numbers): Hundreds digits are8, 0, 0, 0, 0, 1, 0, 0. Stable grouping by hundreds digit gives:[2, 24, 45, 66, 75, 90, 170, 802].
Graphical Representation: Stepwise LSD Passes on [170, 45, 75, 90, 802, 24, 2, 66]
4. Time & Space Complexity Analysis
| Metric | Complexity | Exam Explanation |
|---|---|---|
| Best, Average & Worst Time | O(d · (n + b)) |
d passes; each pass runs stable counting sort over n elements and base b (b = 10 for decimal) |
When d Is Constant & b = O(1) |
O(n) |
Linear time when numbers have a fixed maximum number of digits |
| Auxiliary Space | O(n + b) |
Temporary output array of size n plus frequency/count array of size b |
5. C Program: Radix Sort (LSD with Counting Sort)
#include <stdio.h>
int getMax(int arr[], int n) {
int mx = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > mx)
mx = arr[i];
}
return mx;
}
void countingSortByDigit(int arr[], int n, int exp) {
int output[n];
int count[10] = {0};
// Count occurrences of each digit at current place (exp)
for (int i = 0; i < n; i++) {
int digit = (arr[i] / exp) % 10;
count[digit]++;
}
// Cumulative counts to compute positions
for (int i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
// Build output array from right to left to maintain stability
for (int i = n - 1; i >= 0; i--) {
int digit = (arr[i] / exp) % 10;
output[count[digit] - 1] = arr[i];
count[digit]--;
}
// Copy back to arr[]
for (int i = 0; i < n; i++) {
arr[i] = output[i];
}
}
void radixSort(int arr[], int n) {
int m = getMax(arr, n);
for (int exp = 1; m / exp > 0; exp = 10) {
countingSortByDigit(arr, n, exp);
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
printArray(arr, n);
radixSort(arr, n);
printf("Sorted array (Ascending): ");
printArray(arr, n);
return 0;
}
Expected Output (C):
Original array: 170 45 75 90 802 24 2 66
Sorted array (Ascending): 2 24 45 66 75 90 170 802
6. Python Program: Radix Sort
def counting_sort_by_digit(arr, exp):
n = len(arr)
output = [0] n
count = [0] 10
for num in arr:
digit = (num // exp) % 10
count[digit] += 1
for i in range(1, 10):
count[i] += count[i - 1]
for i in range(n - 1, -1, -1):
digit = (arr[i] // exp) % 10
output[count[digit] - 1] = arr[i]
count[digit] -= 1
return output
def radix_sort(arr):
if not arr:
return []
a = arr[:]
max_val = max(a)
exp = 1
while max_val // exp > 0:
a = counting_sort_by_digit(a, exp)
exp *= 10
return a
if __name__ == "__main__":
data = [170, 45, 75, 90, 802, 24, 2, 66]
print("Original array:", data)
print("Sorted array (Ascending):", radix_sort(data))
Expected Output (Python):
Original array: [170, 45, 75, 90, 802, 24, 2, 66]
Sorted array (Ascending): [2, 24, 45, 66, 75, 90, 170, 802]