0
0
DSA C++programming~30 mins

Counting Sort Algorithm in DSA C++ - Build from Scratch

Choose your learning style9 modes available
Counting Sort Algorithm
📖 Scenario: You work in a warehouse where packages are labeled with numbers from 0 to 9. You want to sort these package labels quickly to organize them for delivery.
🎯 Goal: Build a program that uses the Counting Sort Algorithm to sort a list of package labels (numbers from 0 to 9) efficiently.
📋 What You'll Learn
Create an array called packages with the exact values: 4, 2, 2, 8, 3, 3, 1
Create a count array called count with size 10 initialized to 0
Implement the counting sort logic to fill the count array with frequencies of each number in packages
Use the count array to reconstruct the sorted packages array
Print the sorted packages array separated by spaces
💡 Why This Matters
🌍 Real World
Counting sort is useful in sorting items with small ranges quickly, like sorting grades, ages, or package labels.
💼 Career
Understanding counting sort helps in optimizing sorting tasks in software development and data processing roles.
Progress0 / 4 steps
1
Create the initial array of package labels
Create an integer array called packages with these exact values: 4, 2, 2, 8, 3, 3, 1
DSA C++
Hint

Use curly braces {} to list the numbers inside the array.

2
Create the count array to store frequencies
Create an integer array called count of size 10 and initialize all elements to 0
DSA C++
Hint

Use {0} to initialize all elements to zero.

3
Count the frequency of each number in packages
Use a for loop with variable i from 0 to 6 to increment count[packages[i]] by 1
DSA C++
Hint

Loop through each element in packages and increase the count for that number.

4
Rebuild the sorted array and print it
Use two for loops: the outer loop with variable num from 0 to 9, and the inner loop with variable j from 0 to count[num] to overwrite packages with sorted numbers. Then print the sorted packages separated by spaces.
DSA C++
Hint

Use nested loops to fill packages with sorted numbers and then print them with spaces.