0
0
DSA C++programming~3 mins

Why Counting Sort Algorithm in DSA C++?

Choose your learning style9 modes available
The Big Idea

What if you could sort thousands of items instantly just by counting them first?

The Scenario

Imagine you have a big box of colored balls, and you want to arrange them by color quickly. If you try to pick each ball and compare it with every other ball to find its place, it will take a very long time.

The Problem

Sorting by comparing each ball to others is slow and tiring. It can take a lot of time, especially if you have many balls. Also, it is easy to make mistakes when comparing many items one by one.

The Solution

Counting Sort solves this by counting how many balls of each color you have first. Then, it uses these counts to place each ball directly in the right order without comparing them one by one. This makes sorting very fast and simple.

Before vs After
Before
for (int i = 0; i < n - 1; i++) {
  for (int j = i + 1; j < n; j++) {
    if (arr[i] > arr[j]) {
      std::swap(arr[i], arr[j]);
    }
  }
}
After
int count[maxValue + 1] = {0};
for (int i = 0; i < n; i++) {
  count[arr[i]]++;
}
int index = 0;
for (int i = 0; i <= maxValue; i++) {
  while (count[i]-- > 0) {
    arr[index++] = i;
  }
}
What It Enables

Counting Sort enables lightning-fast sorting when you know the range of values, making tasks like organizing or searching much easier.

Real Life Example

Think about sorting exam scores from 0 to 100. Counting Sort quickly counts how many students got each score and then lists the scores in order without comparing each student's score to others.

Key Takeaways

Manual comparison sorting is slow and error-prone for large data.

Counting Sort counts occurrences to sort efficiently without direct comparisons.

This method is perfect when sorting numbers within a known small range.