Algorithm


Counting Sort Algorithm:

  1. Start with an unsorted array of integers within a known range.
  2. Create a count array to store the frequency of each distinct integer:
    1. Iterate through the original array to populate the count array.
    2. Each index in the count array represents an integer and its frequency.
  3. Transform the count array to store cumulative counts:
    1. Cumulative counts represent the position of integers in the sorted array.
  4. Build the sorted array:
    1. Iterate through the original array in reverse order for stability.
    2. Place each integer at its correct position using the cumulative counts.
    3. Decrease the count in the count array after placing each integer.
  5. Replace the original array with the sorted array.

Example:

Counting Sort Example

Fig. 1: Iteration by Iteration Visualization of Counting Sort

Note: Counting Sort is non-comparison-based and works best for integers within a small range.