简体   繁体   English

Java位操作(在Radix Sort中)

[英]Java Bit Operations (In Radix Sort)

The other day I decided to write an implementation of radix sort in Java. 前几天,我决定用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. 基数排序应该是O(k * N),但由于将每个数字分解为一个数字的过程,我的最终结果是O(k ^ 2 * N)。 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. 现在,我的问题是:哪种方法最能分解Java中的每个数字,1)上述方法。 2) Convert number to String and use substrings. 2)将数字转换为字符串并使用子字符串。 3) Use bit operations. 3)使用位操作。

If 3) then how would that work? 如果3)那将如何工作?

As a hint, try using a radix other than 10, since computers handle binary arithmetic better than decimal. 提示一下,请尝试使用非10的基数,因为计算机处理二进制算术要好于十进制。

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

By the way, Java's >> performs sign extension, which is probably not what you want in this case. 顺便说一下,Java的>>执行符号扩展,在这种情况下可能不是您想要的。 Use >>> instead. 使用>>>代替。

Radix_sort_(Java) 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. &是用于按位与的运算符,而>>是右移。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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