Counting Sort Python (original) (raw)

Last Updated : 12 Nov, 2025

Counting Sort is a non-comparison-based sorting algorithm. It is highly efficient when the range of input values is small compared to the number of elements. The main idea is to count the occurrences of each element and then use these counts to determine the correct position of each element in the sorted output.

Working of Counting Sort

  1. Find the maximum element in the input array.
  2. Initialize a countArray of size max + 1 with all zeros.
  3. Store the frequency of each element from the input array at its corresponding index in countArray.
  4. Example: if 2 appears twice, countArray[2] = 2.
  5. Convert countArray into prefix sum each index now shows the final position of that element in the sorted order.
  6. Build the output array by iterating the input array from the end (to maintain stability).
  7. Copy output back to the input array.

Algorithm

  1. Create a count array "countArray[max(input)+1]" initialized to 0.
  2. For each element in inputArray, increment countArray[element].
  3. Compute prefix sums in countArray.
  4. Create an empty outputArray of size N.
  5. Traverse input from the end and place each element at countArray[element] -1.
  6. Decrement countArray[element] after each placement.

Python Implementation

Python `

def countSort(arr): max_val = max(arr) count = [0] * (max_val + 1) output = [0] * len(arr)

for num in arr:
    count[num] += 1

for i in range(1, len(count)):
    count[i] += count[i - 1]

for num in reversed(arr):
    output[count[num] - 1] = num
    count[num] -= 1

for i in range(len(arr)):
    arr[i] = output[i]

return arr

arr = [4, 2, 2, 8, 3, 3, 1] sorted_arr = countSort(arr) print("Sorted array is:", sorted_arr)

`

Output

Sorted array is: [1, 2, 2, 3, 3, 4, 8]

**Explanation:

Counting Sort Using collections.Counter

The traditional Counting Sort manually counts occurrences and builds prefix sums using arrays. Python's collections.Counter offers a simpler way to achieve the same result, it automatically counts element frequencies.

The logic remains the same:

Using Counter, we skip manual array handling and directly rebuild the sorted output by iterating over sorted keys.

Python Implementation

Python `

from collections import Counter

def count_sort(arr): count = Counter(arr) res = [] for num in sorted(count.keys()): res += [num] * count[num] return res

arr = [4, 2, 2, 8, 3, 3, 1] sort_arr = count_sort(arr) print( sort_arr)

`

Output

[1, 2, 2, 3, 3, 4, 8]

**Explanation: