Radix sort in Java



/** frequency of the byte */
public static int[] freq = new int[256];

/** number of positions */
public static final int KEYLEN = 4;

/** Get the value of the position i. */
public static int getValue (int key, int i) {
return (key >>> (8*i))&0xff;
} // getValue

/** Sort non-negative keys by position i in a stable manner. */
public static int[] countSort (int[] keys, int i) {
if (keys == null) return null;
int[] res = new int [keys.length];
for (int k=0; k < freq.length; k++) {
freq [k] = 0;
}
for (int j=0; j < keys.length; j++) {
freq [getValue (keys[j], i)]++;
}
for (int k=1; k < freq.length; k++) {
freq [k] = freq[k-1] + freq[k];
}
for (int j=keys.length-1; j >= 0; j--) {
int ind = --freq [getValue (keys[j], i)];
res[ind] = keys[j];
}
return res;
} // countSort

/** Radix sort for non-negative integers. */
public static void radixSort (int[] keys) {
if (keys == null) return;
int[] res = keys;
for (int p=0; p < KEYLEN; p++) {
res = countSort (res, p);
}
for (int i=0; i < keys.length; i++) {
keys[i] = res[i];
}
} // radixSort


Jaanus Pöial