E
E
Eze2014-01-28 14:16:30
Java
Eze, 2014-01-28 14:16:30

Problem with Radix Sort

I'm learning radix sort. Found the following implementation:
public static void radixSort(int[] arr) {
int numBytes = 4; // for ints
int cnt[][] = new int[numBytes][257];
int b[] = new int[arr.length];
for (int j = 0; j < numBytes; j++) {
// count the number of elements for each value of the j-th digit
for (int i = 0; i < arr.length; i++) {
cnt[j][1 + iByteN (arr[i], j)]++;
}
//calculate positions cnt[i], starting from which elements will be located
//with the corresponding value of the j-th digit
for (int i = 1; i < 257; i++)
cnt[j][i] += cnt[j ][i - 1];
// arrange elements from array a to array b in the specified order
for (int i = 0; i < arr.length; i++) {
b[cnt[j][iByteN(arr[i], j)]++] = arr[i];
}
// copy array b to array a
for (int i = 0; i < arr.length; i++)
arr[i] = b[i];
//arr = b;
}
}
public static int iByteN(int n, int i) {
return (n >> (8 * i)) & 255;
}
I like this implementation, it's simple, but I can't understand why in the cnt array, subarrays are created with a length of 257 and not 256 ? After all, a byte takes values ​​from 0 to 255, that is, an array of 256 ints is enough.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2014-01-28
@Eze

In order not to put a condition in
for (int i = 0; i < arr.length; i++) {
cnt[j][1 + iByteN(arr[i], j)]++;
}
?
If you do this, it also works:

int cnt[][] = new int[numBytes][256];
                int b[] = new int[arr.length];

                for (int j = 0; j < numBytes; j++) {
                        // подсчитываем количество элементов для каждого значения j-го разряда
                        for (int i = 0; i < arr.length; i++) {
                                if (iByteN(arr[i], j) < 255)
                                        cnt[j][1 + iByteN(arr[i], j)]++;
                        }
                        //вычисляем позиции cnt[i], начиная с которых будут располагаться элементы
                        //с соответствующим значением j-го разряда
                        for (int i = 1; i < 256; i++)
                                cnt[j][i] += cnt[j][i - 1];
...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question