0
0
DSA Javascriptprogramming~3 mins

Why Counting Sort Algorithm in DSA Javascript?

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 long time and be very tiring.

The Problem

Sorting by comparing each ball to every other ball is slow and confusing. It's easy to make mistakes, and it takes a lot of time, especially when there are many balls. This manual way doesn't use the fact that colors are limited and known.

The Solution

Counting Sort counts how many balls of each color there are first. Then, it uses these counts to place each ball directly in the right order. This way, it sorts very fast without comparing every ball to every other ball.

Before vs After
Before
function manualSort(arr) {
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] > arr[j]) {
        let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;
      }
    }
  }
  return arr;
}
After
function countingSort(arr, max) {
  const count = new Array(max + 1).fill(0);
  for (const num of arr) count[num]++;
  let index = 0;
  for (let i = 0; i <= max; i++) {
    while (count[i] > 0) {
      arr[index++] = i;
      count[i]--;
    }
  }
  return arr;
}
What It Enables

Counting Sort enables lightning-fast sorting when you know the range of values, making big sorting tasks simple and efficient.

Real Life Example

Imagine sorting exam scores that range only from 0 to 100. Counting Sort quickly counts how many students got each score and then lists them in order without slow comparisons.

Key Takeaways

Manual sorting by comparing each item is slow and error-prone.

Counting Sort counts occurrences and places items directly.

This method is fast when the range of values is small and known.