What if you could sort thousands of items instantly just by counting them first?
Why Counting Sort Algorithm in DSA C++?
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.
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.
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.
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]); } } }
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; } }
Counting Sort enables lightning-fast sorting when you know the range of values, making tasks like organizing or searching much easier.
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.
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.