简体   繁体   中英

Java Bit Operations (In Radix Sort)

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?

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM