# Counting Sort – Data Structures and Algorithms

Counting Sort actively operates by categorizing elements into distinctive groups, known as counts. These counts are derived from the frequencies of each input element. After tallying the counts, subsequent steps involve computing the prefix sum of the counts, determining the correct positions of elements in the sorted output array. The culmination of these steps results in a precisely ordered sequence of elements.

## Counting Sort algorithm

The Counting Sort algorithm begins with the creation of a count array to store the frequencies of input elements. For each element ‘arr[i]’ in the array, the following actions are taken:

1. Frequency Counting: Increment the count for the element ‘arr[i]’ in the count array.
2. Prefix Sum Calculation: Calculate the prefix sum of the count array to determine the positions of elements in the sorted output.
3. Sorting Procedure: Place elements into their correct positions in the sorted output array based on the prefix sum.

In essence, this algorithm systematically organizes elements by categorizing them according to their frequencies, followed by determining their sorted positions based on the prefix sum. This orchestrated process ultimately leads to a comprehensive and sorted arrangement of the elements.

## Working of Counting Sort Algorithm

Certainly, I’ll provide a table with an explanation column for each step of the Counting Sort process:

Explanation for each step has been added to the table. This should help you understand the process of Counting Sort and how the count array, prefix sum array, and sorted output array evolve at each step.

## Complexity Analysis

### Time Complexity:

• Frequency counting and prefix sum calculation: O(n), where ‘n’ is the number of elements.
• Sorting procedure: O(n). Overall time complexity: O(n + n) = O(n).

### Space Complexity

The auxiliary space complexity primarily depends on the range of input values. It generally stands at O(k), where ‘k’ is the range of possible values.

In conclusion, Counting Sort offers an effective methodology for sorting elements by categorizing them based on their frequencies. Through frequency counting, prefix sum calculation, and appropriate positioning, this technique ensures a streamlined sorting process. Counting Sort’s suitability for scenarios with a limited range of values highlights its practicality and effectiveness in specific sorting contexts.