Implement Radix Sort. Sort integers by processing individual digits from least significant to most significant, using a stable sort (counting sort) as a subroutine.
Input: [170, 45, 75, 90, 802, 24, 2, 66] → Output: [2, 24, 45, 66, 75, 90, 170, 802]Input: [329, 457, 657, 839, 436, 720, 355] → Output: [329, 355, 436, 457, 657, 720, 839]
Sort numbers digit by digit starting from the least significant digit (ones place). For each digit position, apply a stable counting sort using that digit as the key.
- Find the maximum number to determine the number of digits.
- For each digit position (1, 10, 100, ...): do a stable counting sort by that digit.
- Use modulo and division to extract each digit.
- After processing all digit positions, array is sorted.
import java.util.Arrays;
class RadixSort {
public void sort(int[] arr) {
int max = Arrays.stream(arr).max().getAsInt();
for (int exp = 1; max / exp > 0; exp *= 10)
countingSortByDigit(arr, exp);
}
private void countingSortByDigit(int[] arr, int exp) {
int n = arr.length;
int[] output = new int[n];
int[] count = new int[10];
for (int v : arr) count[(v / exp) % 10]++;
for (int i = 1; i < 10; i++) count[i] += count[i - 1];
for (int i = n - 1; i >= 0; i--)
output[--count[(arr[i] / exp) % 10]] = arr[i];
System.arraycopy(output, 0, arr, 0, n);
}
}
- Time Complexity: O(D * (N + K)) where D=digits, K=10
- Space Complexity: O(N + K)