Please refer to the following code for radix sort:
class RadixSort
{
public static void radix_sort_uint(int[] a, int bits)
{
int[] b = new int[a.length];
int[] b_orig = b;
int rshift = 0;
for (int mask = ~(-1 << bits); mask != 0; mask <<= bits, rshift += bits) {
int[] cntarray = new int[1 << bits];
for (int p = 0; p < a.length; ++p) {
int key = (a[p] & mask) >> rshift;
++cntarray[key];
}
for (int i = 1; i < cntarray.length; ++i)
cntarray[i] += cntarray[i-1];
for (int p = a.length-1; p >= 0; --p) {
int key = (a[p] & mask) >> rshift;
--cntarray[key];
b[cntarray[key]] = a[p];
}
int[] temp = b; b = a; a = temp;
}
if (a == b_orig)
System.arraycopy(a, 0, b, 0, a.length);
}
}
This is downloaded from wikipedia.
I feel that the algorithm will work only for value of bits
parameter that divide 32 perfectly. Thus, bits
should be something like 2 or 4 , but not 10. P开发者_开发百科lease let me know if I am right.
Short answer: No
Long answer:
The probable line of confusion is:
for (int mask = ~(-1 << bits); mask != 0; mask <<= bits, rshift += bits) {
mask <<= bits
shifts the bits of mask
left by bits
, padding the right with zeros. If bits
doesn't divide 32, then the full 32 bits won't be utilised. So while bits
should divide 32, choosing a value that doesn't does not break the code.
精彩评论