【问题标题】:cant figure out how to fix the bug无法弄清楚如何修复错误
【发布时间】: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


【解决方案1】:

你得到重复的原因是:

 int temp = A[i - 1];
 B[i - 1] = B[i];
 B[i] = temp;

您从 A 获取 temp 并将其设置为 B。这将停止重复,但不会修复您的排序。基数排序使用桶来确定排序顺序(这就是第二个数组的原因),彼此之间没有比较。你正在做一种修改过的交换。

【讨论】:

    猜你喜欢
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2015-10-26
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多