Radix Sort is a non-comparison-based sorting algorithm that sorts numbers by processing their individual digits. It works by sorting the input numbers digit by digit, starting from the least significant digit (LSD) to the most significant digit (MSD).
Unlike traditional comparison sorts (like Quick Sort or Merge Sort), Radix Sort does not compare elements directly. Instead, it groups numbers by each digit using a stable sorting algorithm (commonly Counting Sort) as a subroutine.
For example, to sort numbers by the hundreds place, we ensure the list is already stably sorted by the tens and units digits.
Use Radix Sort when:
| Factor | Complexity |
|---|---|
| Time | O(n * k) |
| Space | O(n + k) |
Where:
n = number of elementsk = number of digits in the largest numberk ≈ log₁₀(max element))public class RadixSortExample {
// Main radix sort method
public static void radixSort(int[] arr) {
int max = getMax(arr);
// Apply counting sort for each digit (LSD to MSD)
for (int exp = 1; max / exp > 0; exp *= 10) {
countingSortByDigit(arr, exp);
}
}
// Helper method to get the maximum value
public static int getMax(int[] arr) {
int max = arr[0];
for (int num : arr) {
if (num > max) max = num;
}
return max;
}
// Counting Sort based on the current digit (exp)
public static void countingSortByDigit(int[] arr, int exp) {
int n = arr.length;
int[] output = new int[n];
int[] count = new int[10]; // For digits 0–9
// Count digit occurrences
for (int i = 0; i < n; i++) {
int digit = (arr[i] / exp) % 10;
count[digit]++;
}
// Convert count to position indices
for (int i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
// Build the output array (stable sort)
for (int i = n - 1; i >= 0; i--) {
int digit = (arr[i] / exp) % 10;
output[count[digit] - 1] = arr[i];
count[digit]--;
}
// Copy sorted output back into original array
System.arraycopy(output, 0, arr, 0, n);
}
public static void printArray(int[] arr) {
for (int value : arr) {
System.out.print(value + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {170, 45, 75, 90, 802, 24, 2, 66};
System.out.println("Original array:");
printArray(arr);
radixSort(arr);
System.out.println("Sorted array:");
printArray(arr);
}
}
Original array:
170 45 75 90 802 24 2 66
Sorted array:
2 24 45 66 75 90 170 802
Let’s sort this array:
[170, 45, 75, 90, 802, 24, 2, 66]
Sort by last digit:
[170, 90, 802, 2, 24, 45, 75, 66]
→ Sorted: [170, 90, 802, 2, 24, 45, 75, 66]
Last digits: 0, 5, 5, 0, 2, 4, 2, 6
→ After stable sort:
[170, 90, 802, 2, 24, 45, 75, 66]
Digits: 7, 4, 7, 9, 0, 2, 6, 6
→ After stable sort:
[802, 2, 24, 45, 66, 75, 170, 90]
Digits: 8, 0, 0, 0, 0, 0, 1, 0
→ After stable sort:
[2, 24, 45, 66, 75, 90, 170, 802]
[2, 24, 45, 66, 75, 90, 170, 802]