Skip to content

Instantly share code, notes, and snippets.

@agustarc
Created December 21, 2016 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agustarc/f8a35f4dfdd260cb7ccffe484c6e0d80 to your computer and use it in GitHub Desktop.
Save agustarc/f8a35f4dfdd260cb7ccffe484c6e0d80 to your computer and use it in GitHub Desktop.
public class RadixSort {
@SuppressWarnings("unchecked")
private static LinkedList<Integer>[] counter = new LinkedList[] {
new LinkedList<>(), new LinkedList<>(),
new LinkedList<>(), new LinkedList<>(),
new LinkedList<>(), new LinkedList<>(),
new LinkedList<>(), new LinkedList<>(),
new LinkedList<>(), new LinkedList<>() };
public static void radixSort(int[] arr) {
int max = Integer.MIN_VALUE;
for (int element : arr) {
if (element > max) {
max = element;
}
}
final int maxDigit = String.valueOf(max).length();
radixSort(arr, maxDigit);
}
private static void radixSort(int[] arr, int digitCount) {
int mod = 10;
int div = 1;
for (int i = 0; i < digitCount; i++, div *= 10, mod *= 10) {
for (final int element : arr) {
final int bucket = element % mod / div;
counter[bucket].add(element);
}
int pos = 0;
for (final LinkedList<Integer> element : counter) {
Integer value;
while ((value = element.poll()) != null) {
arr[pos++] = value;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment