Counting Sort

Mental Model:

  1. Get range of collection
  2. Create counts array (of length equal to range)
  3. Count occurrences of each element i and store in counts[i]
  4. Sum each position of the element with predecessors.
  5. 💡
    Now, counts[i] shows # of elements <= i in the collection
  6. Create an output array
  7. Populate the output such that:
  8. 💡
    output[ of the position of collection[i] in the counts array (which is sorted) ] = collection[i]

Runtime: O(n)O(n)