Counting Sort

Counting Sort is a Distributive sorting algorithm that can only sort integers. its time complexity is $$O(n+m)$$, where m is the largest number. it is stable, not adaptive, and uses $$O(m)$$ memory.

= Explanation = First, compute a histogram of the key values, then preforming a prefix sum calculation to determine the positions of the output values.

= Example = take the array {12 6 7 8 5 4 10 13 11 1 14 2 15 9 16 3}.

first, compute a histogram: {0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1}

apply prefix sum: {0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16}

determine positions of input values...

{1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16}

Sorted!

= Pseudocode = procedure counting_sort(array arr) do array output = array of length(arr) 0s array histogram = array of max(arr) + 1 0s for i = 0 to length(arr) - 1 do histogram[arr[i]] ++ end for for i = 1 to max(arr) do histogram[i] += histogram[i - 1] end for for i = length(arr) - 1 to 0 do count[arr[i]] -- output[count[arr[i]]] = arr[i] end for arr = output end