【发布时间】:2013-12-02 04:14:27
【问题描述】:
使用 JAVA,我尝试通过基数排序对整数数组(升序)进行排序,但似乎没有解决问题。
public class Ex_radix {
public static void radixSort(int[] A) {
int d = 0;
for (int digit = 0; digit < A.length; digit++) {// Checks what is the
// maximum amount of
// digits in any number
int num = A[digit];
int counter = 0;
while (num != 0) {
num = num / 10;
counter = counter + 1;
}
if (counter > d) {
d = counter;
}
}
System.out.println("this is the max number of digits: " + d);
int[] B = new int[A.length];// Copying the array
for (int j = 0; j < A.length; j++) {
B[j] = A[j];
System.out.println("this is cell " + j + ": " + B[j]);
}
int iteration = 1;//Starting sort
while (iteration <= d) {
for (int i = 1; i < B.length; i++) {
if (B[i] % (10 ^ iteration) < B[i - 1] % (10 ^ iteration)) {
int temp = A[i - 1];
B[i - 1] = B[i];
B[i] = temp;
}
}
for (int i = 0; i < B.length; i++) {// Checking
System.out.print(B[i] + ", ");
}
System.out.println();
iteration = iteration + 1;
}
}
public static void main(String[] args) {
int[] C = { 329, 457, 657, 839, 436, 720, 355 };
radixSort(C);
}
}
如果您运行它,您会看到它开始正常,但在第一次迭代中,下一个数字被复制。 我尝试了几种方法,但无法弄清楚。
第一次迭代:457、657、839、436、839、355、720、 第二次迭代:457、657、436、657、355、720、720、 第三次迭代:657、436、657、657、720、720、720,
【问题讨论】:
-
^不是幂运算。您可以使用Math.pow,但我会保留另一个变量powerOf10,它拥有“10 的迭代 幂”。然后,当您将 1 加到iteration时,我敢打赌您可以猜到如何处理powerOf10。 -
正确。我解决了这个问题,我太傻了。但它仍然不能解决问题。我仍然收到复制的号码。
标签: java arrays radix-sort