Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions src/sorting/counting_sort/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# 🧠 Counting Sort

## 📝 Description

Counting Sort is a non-comparison-based sorting algorithm that operates by counting the occurrences of each distinct element in the input sequence and using this information to place each element directly into its correct position in the output sequence. It is suitable for sorting a collection of elements where the keys are integers within a known, finite, and reasonably small range.

## 💾 Time Complexity

| Case | Complexity |
| ----- | ---------- |
| Best | $O(n+k)$ |
| Worst | $O(n+k)$ |

Where:

- $n$ is the number of elements in the input array.
- $k$ is the range of input values.

## 💾 Space Complexity

The space complexity is $O(n+k)$, as it requires:

- An auxiliary count array of size $k$
- An output array of size $n$

## 💡 Intuition By Analogy

Imagine you have a bag full of coins. You start by making one stack for each different kind of coin, organized in ascending order. Then, you disassemble the stacks and lay out the coins in order. Now you have a series of sorted coins, without ever comparing one coin directly to another.

## 🧾 Pseudocode

```
CountingSort(array, max_value)
Let count be an array with a length equal to max_value. All elements are in count are equal to -1.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All elements shall be at 0
e.g
https://en.wikipedia.org/wiki/Counting_sort

Ler output be an array of same length as array
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let *


Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add comment
// count occurence, of each element,

for i in array:
count[i - 1] = count[i - 1] + 1

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

// Calculate cumulative count (position)

for i to length(count) - 1:
count[i + 1] = count[i + 1] + count[i]

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

// Place elements in sorted order

for i to length(array):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for i = length(array)-1 down to 0:
output[count[array[i]]-1] = array[i]
count[array[i]] -= 1

element = array[i] - 1
count[element] -= 1
output[count[element]] = array[i]

return output
```

## 📈 Time Complexity Analysis

### Step-by-step:

1. Initialize count and output arrays → $O(k+n)$
2. First loop (counting occurrences) → $O(n)$
3. Second loop (prefix sums) → $O(k)$
4. Third loop (placing elements in output) → $O(n)$

Therefore the overall complexity is $O(k+n)$.
This holds for **best**, **worst**, and **average** cases because Counting Sort's steps don't depend on the order of the input, only on the size of nn and range $k$.
1 change: 1 addition & 0 deletions src/sorting/counting_sort/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Counting sort implementation package for sorting algorithms."""
38 changes: 38 additions & 0 deletions src/sorting/counting_sort/counting_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""Counting Sort Algorithm."""


def counting_sort(array: list[int], max_value: int) -> list[int]:
"""Sort a list of integers from 1 to max_value using counting sort.

Parameters
----------
array : list[Any]
The list of integers from 1 to max_value.

max_value : int
The maximum value inside the array.

Returns
-------
list[Any]
The same list, sorted in ascending order.

"""
count = [0] * max_value
output = [-1] * len(array)

# counting elements in array
for i in array:
count[i - 1] += 1

# weighting of counting
for i in range(len(count) - 1):
count[i + 1] = count[i + 1] + count[i]

# sorting using count
for i in range(len(array)):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This shall be in reversed order

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

    for num in reversed(array):  # Process in reverse for stability
        index = count[num - 1] - 1
        output[index] = num
        count[num - 1] -= 1

element = array[i] - 1
count[element] -= 1
output[count[element]] = array[i]

return output
1 change: 1 addition & 0 deletions tests/sorting/counting_sort/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Test package for counting sort implementation."""
Empty file.
1 change: 1 addition & 0 deletions tests/sorting/counting_sort/test_counting.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Tests for counting sort algorithm implementation."""