Skip to content

Instantly share code, notes, and snippets.

@lnsp
Last active September 13, 2015 16:21
Show Gist options
  • Save lnsp/682c787a4be4eed9fc66 to your computer and use it in GitHub Desktop.
Save lnsp/682c787a4be4eed9fc66 to your computer and use it in GitHub Desktop.
A simple radix sort implementation based on arrays
public static void sort(int[] a) {
int largestNumber = 0;
// find largest number
for (int n : a)
if (largestNumber < n) largestNumber = n;
// calculate needed iterations
final int maxIterations = (int) Math.log10(largestNumber) + 1;
// create buckets
int[][] buckets = new int[10][a.length];
int[] bucketIterator = new int[10];
// run radix
for (int i = 0; i < maxIterations; i++) {
// put values in buckets
for (int j = 0; j < a.length; j++) {
int value = a[j];
// shrink number
if (i > 0)
value /= i * 10;
// get current digit
int digit = value % 10;
// put in bucket
buckets[digit][bucketIterator[digit]] = a[j];
// increase bucket iterator
bucketIterator[digit]++;
}
// copy values back in array
int arrayIndex = 0;
for (int digit = 0; digit < 10; digit++) {
// run per digit
for (int bucketIndex = 0; bucketIndex < bucketIterator[digit]; bucketIndex++) {
a[arrayIndex] = buckets[digit][bucketIndex];
// clean index
buckets[digit][bucketIndex] = 0;
// increase array index
arrayIndex++;
}
// clean iterator
bucketIterator[digit] = 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment