Search code examples
javasortingcounting-sort

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}
  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. I've tried but can't seem to find how this is happening.

Solution

  • The loop for counting occurrences doesn't iterate over all elements, you are skipping the 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);