简体   繁体   English

计数排序Java-意外结果

[英]Counting sort Java - Unexpected results

class CountingSort {

    int[] csort(int[] arr) {
        int n = arr.length;
        int max = arr[0];
        int[] out = new int[n];
        for (int i : arr) {
            if (max < i) {
                max = i;
            }
        }
        int range = max + 1;
        int[] te = new int[range];
        for (int i = 0; i < range; ++i) {
            te[i] = 0;
        }
        for (int j = 1; j < n; j++) {
            te[arr[j]] = te[arr[j]] + 1;
        }
        // case1: {0,0,0,1,0,1,1,0,1,1}
        // case2: {0,0,0,1,0,1,1,0,1,1}
        for (int k = 1; k < range; ++k) {
            te[k] = te[k] + te[k - 1];
        }
        // case1: {0,0,0,1,1,2,3,3,4,5}
        // case2: {0,0,0,1,1,2,3,3,4,5}
        for (int l = n - 1; l >= 0; --l) {
            out[te[arr[l]]] = arr[l];
            te[arr[l]] = te[arr[l]] - 1;
        }
        return out;
    }

}

Above is the code for Counting Sort. 上面是计数排序的代码。 Following are my observations 以下是我的观察

  1. if the input array such that smallest is first element eg {1, 6, 8, 3, 5, 9} it gives the expected output {1, 3, 5, 6, 8, 9} 如果输入数组使得最小值是第一个元素,例如{1, 6, 8, 3, 5, 9}则给出预期的输出{1, 3, 5, 6, 8, 9}
  2. But if give the input array such that first element is not the smallest eg {4, 6, 8, 3, 5, 9} then the output has first element zero and one number goes missing. 但是,如果给输入数组一个第一个元素不是最小的元素,例如{4, 6, 8, 3, 5, 9}那么输出的第一个元素为零,一个数字丢失了。 I've tried but can't seem to find how this is happening. 我已经尝试过,但似乎找不到这种情况。

The loop for counting occurrences doesn't iterate over all elements, you are skipping the arr[0] . 计数出现次数的循环不会遍历所有元素,您将跳过arr[0]

for (int j = 0; j < n; j++) {
    te[arr[j]] = te[arr[j]] + 1;
}

Besides, you could write it in a more "elegant" way: 此外,您可以用更“优雅”的方式编写它:

for (int j = 0; j < n; ++te[arr[j]], ++j);

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

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