Skip to content

Instantly share code, notes, and snippets.

@maycuatroi1
Created October 26, 2025 22:52
Show Gist options
  • Select an option

  • Save maycuatroi1/8270fe20078b68287a81dc34567f919e to your computer and use it in GitHub Desktop.

Select an option

Save maycuatroi1/8270fe20078b68287a81dc34567f919e to your computer and use it in GitHub Desktop.
public class RadixSort {
public static void radixSort(int[] arr) {
if (arr.length == 0) {
return;
}
// Find the maximum number to know number of digits
int max = getMax(arr);
// Do counting sort for every digit
// exp is 10^i where i is current digit number
for (int exp = 1; max / exp > 0; exp *= 10) {
countingSortByDigit(arr, exp);
}
}
// A utility function to get maximum value in arr[]
private static int getMax(int[] arr) {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
// A function to do counting sort of arr[] according to
// the digit represented by exp
private static void countingSortByDigit(int[] arr, int exp) {
int n = arr.length;
int[] output = new int[n]; // output array
int[] count = new int[10];
// Initialize count array
for (int i = 0; i < 10; i++) {
count[i] = 0;
}
// Store count of occurrences in count[]
for (int i = 0; i < n; i++) {
int digit = (arr[i] / exp) % 10;
count[digit]++;
}
// Change count[i] so that count[i] now contains
// actual position of this digit in output[]
for (int i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
// Build the output array
for (int i = n - 1; i >= 0; i--) {
int digit = (arr[i] / exp) % 10;
output[count[digit] - 1] = arr[i];
count[digit]--;
}
// Copy the output array to arr[]
for (int i = 0; i < n; i++) {
arr[i] = output[i];
}
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
System.out.println("Original array:");
printArray(arr);
radixSort(arr);
System.out.println("Sorted array:");
printArray(arr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment