Counting Sort - Code

Implementation and analysis.

Here is the implementation of counting sort:

function countingSort(arr, k):
    n = arr.length
    count = array of size k+1, all zeros
    output = array of size n

    // Count occurrences
    for i from 0 to n-1:
        count[arr[i]] = count[arr[i]] + 1

    // Prefix sums
    for i from 1 to k:
        count[i] = count[i] + count[i-1]

    // Build output (iterate backwards for stability)
    for i from n-1 down to 0:
        output[count[arr[i]] - 1] = arr[i]
        count[arr[i]] = count[arr[i]] - 1

    return output

Time: O(n+k)O(n + k) where kk is the range of values.

Space: O(n+k)O(n + k) for count and output arrays (excluding input array).

Stability: Stable (if you iterate backwards in the last step).