Created
December 21, 2016 20:35
-
-
Save agustarc/f8a35f4dfdd260cb7ccffe484c6e0d80 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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