Loading

Quipoin Menu

Learn • Practice • Grow

data-structure-with-java / Radix Sort
tutorial

Radix Sort

Radix sort processes digits of numbers from least significant to most significant, using a stable sort (like counting sort) for each digit. It works well for integers and strings. Time O(d * (n + k)), where d is number of digits, k is base.

Java implementation (for non-negative integers):


public static void radixSort(int[] arr) {
int max = Arrays.stream(arr).max().getAsInt();
for (int exp = 1; max / exp > 0; exp *= 10) {
countingSortByDigit(arr, exp);
}
}

private static void countingSortByDigit(int[] arr, int exp) {
int n = arr.length;
int[] output = new int[n];
int[] count = new int[10];
for (int i = 0; i < n; i++) count[(arr[i] / 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] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}
System.arraycopy(output, 0, arr, 0, n);
}
Two Minute Drill
  • Radix sort: O(d * (n + k)) time, O(n + k) space.
  • Non-comparison sort; works on integers and strings.
  • Stable if the digit sort is stable.
  • Ideal for large data with small digit length.

Need more clarification?

Drop us an email at career@quipoinfotech.com