Question

The other day I decided to write an implementation of radix sort in Java. Radix sort is supposed to be O(k*N) but mine ended up being O(k^2*N) because of the process of breaking down each digit to one number. I broke down each digit by modding (%) the preceding digits out and dividing by ten to eliminate the succeeding digits. I asked my professor if there would be a more efficient way of doing this and he said to use bit operators. Now for my questions: Which method would be the fastest at breaking down each number in Java, 1) Method stated above. 2) Convert number to String and use substrings. 3) Use bit operations.

If 3) then how would that work?

Was it helpful?

Solution

As a hint, try using a radix other than 10, since computers handle binary arithmetic better than decimal.

  • x >>> n is equivalent to x / 2n
  • x & (2n - 1) is equivalent to x % 2n

By the way, Java's >> performs sign extension, which is probably not what you want in this case. Use >>> instead.

OTHER TIPS

[http://en.literateprograms.org/Radix_sort_(Java)](http://en.literateprograms.org/Radix_sort_(Java))

The line of code that does this;

 int key = (a[p] & mask) >> rshift;

is the bit manipulation part.

& is the operator to do a bitwise AND and >> is a right-shift.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top