0
0
DSA Javascriptprogramming~30 mins

Counting Sort Algorithm in DSA Javascript - Build from Scratch

Choose your learning style9 modes available
Counting Sort Algorithm
📖 Scenario: You work in a warehouse where boxes are labeled with numbers from 0 to 9. You want to organize the boxes quickly by their labels.
🎯 Goal: Build a program that sorts an array of box labels using the counting sort algorithm.
📋 What You'll Learn
Create an array called boxes with the exact values: [4, 2, 2, 8, 3, 3, 1]
Create an array called count with 10 zeros to count occurrences of each label
Use a for loop with variable label to count each label in boxes
Create an array called sortedBoxes to store the sorted result
Use nested for loops with variables number and i to build sortedBoxes
Print sortedBoxes to show the sorted labels
💡 Why This Matters
🌍 Real World
Counting sort is useful in warehouses or factories where items have labels within a small range and need fast sorting.
💼 Career
Understanding counting sort helps in roles involving data processing, inventory management, and algorithm optimization.
Progress0 / 4 steps
1
Create the initial array of box labels
Create an array called boxes with these exact values: [4, 2, 2, 8, 3, 3, 1]
DSA Javascript
Hint

Use const boxes = [4, 2, 2, 8, 3, 3, 1]; to create the array.

2
Create the count array to hold label counts
Create an array called count with 10 zeros to count occurrences of each label
DSA Javascript
Hint

Use new Array(10).fill(0) to create an array of ten zeros.

3
Count the occurrences of each label
Use a for loop with variable label to increase the count for each label in boxes
DSA Javascript
Hint

Use for (const label of boxes) and increase count[label] by 1 inside the loop.

4
Build the sorted array and print it
Create an empty array called sortedBoxes. Use nested for loops with variables number and i to add each label to sortedBoxes according to its count. Then print sortedBoxes.
DSA Javascript
Hint

Use two loops: outer loop over count indexes, inner loop to push the number count[number] times into sortedBoxes. Then print sortedBoxes.