0
0
DSA C++programming~30 mins

Comparison Based vs Non Comparison Based Sorting in DSA C++ - Build Both Approaches

Choose your learning style9 modes available
Comparison Based vs Non Comparison Based Sorting
📖 Scenario: You work in a warehouse where you need to organize boxes by their weights. Some boxes have small weights (0 to 9 kg), and others have larger weights. You want to sort these boxes quickly using two different methods: one that compares boxes directly and one that uses their weight values without direct comparison.
🎯 Goal: Build two sorting methods in C++: one using comparison-based sorting (Bubble Sort) and one using non-comparison-based sorting (Counting Sort). See how they sort the same list of box weights.
📋 What You'll Learn
Create an array called boxes with these exact weights: 4, 2, 7, 3, 8, 2, 3, 0, 9, 1
Create an integer variable called size that stores the number of boxes
Write a function called bubbleSort that sorts the boxes array using comparison-based sorting
Write a function called countingSort that sorts the boxes array using non-comparison-based sorting
Print the sorted arrays after each sorting method
💡 Why This Matters
🌍 Real World
Sorting items quickly is important in warehouses, online stores, and many apps to organize data efficiently.
💼 Career
Understanding different sorting methods helps in choosing the right algorithm for performance in software development and data processing jobs.
Progress0 / 4 steps
1
Create the boxes array
Create an integer array called boxes with these exact weights: 4, 2, 7, 3, 8, 2, 3, 0, 9, 1 and an integer variable called size that stores the number of boxes.
DSA C++
Hint

Use int boxes[] = {4, 2, 7, 3, 8, 2, 3, 0, 9, 1}; to create the array and int size = sizeof(boxes) / sizeof(boxes[0]); to get its length.

2
Write the bubbleSort function
Write a function called bubbleSort that takes an integer array arr and its size as parameters and sorts the array using comparison-based bubble sort.
DSA C++
Hint

Use two nested loops to compare adjacent elements and swap if the left one is bigger.

3
Write the countingSort function
Write a function called countingSort that takes an integer array arr and its size as parameters and sorts the array using non-comparison-based counting sort. Assume all weights are between 0 and 9.
DSA C++
Hint

Count how many times each weight appears, then overwrite the array with sorted weights.

4
Print sorted arrays after both sorts
Call bubbleSort(boxes, size) and print the sorted array with the label "Bubble Sort:". Then reset boxes to the original array, call countingSort(boxes, size), and print the sorted array with the label "Counting Sort:". Use a for loop with variable i to print elements separated by spaces.
DSA C++
Hint

Call bubbleSort(boxes, size), print the array, reset boxes to original, call countingSort(boxes, size), and print again.