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: where is the range of values.
Space: for count and output arrays (excluding input array).
Stability: Stable (if you iterate backwards in the last step).