📖 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 uses the counting sort algorithm to sort a list of box labels (numbers from 0 to 9) efficiently.
📋 What You'll Learn
Create a vector called boxes with the exact values: [4, 2, 2, 8, 3, 3, 1]
Create a vector 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 a vector called sorted_boxes to store the sorted result
Use nested for loops to build sorted_boxes from count
Print the sorted_boxes vector as the final output
💡 Why This Matters
🌍 Real World
Counting sort is useful in warehouses or inventory systems where items have labels within a small range, allowing fast sorting.
💼 Career
Understanding counting sort helps in jobs involving data processing, optimization, and algorithm design for efficient sorting.
Progress0 / 4 steps
1
Create the initial list of box labels
Create a vector called boxes with these exact values: [4, 2, 2, 8, 3, 3, 1]
DSA Rust
Hint
Use let boxes = vec![4, 2, 2, 8, 3, 3, 1]; to create the vector.
2
Create the count vector to hold label frequencies
Create a vector called count with 10 zeros using vec![0; 10] to count occurrences of each label
DSA Rust
Hint
Use let mut count = vec![0; 10]; to create a mutable vector with 10 zeros.
3
Count the occurrences of each label
Use a for loop with variable label to iterate over boxes and increment count[label] by 1
DSA Rust
Hint
Use for label in &boxes and increment count[*label as usize].
4
Build the sorted list and print it
Create a mutable vector called sorted_boxes. Use a for loop with variable num from 0 to 9, and inside it, use another for loop to push num into sorted_boxescount[num] times. Finally, print sorted_boxes.
DSA Rust
Hint
Use nested loops to push numbers into sorted_boxes and then print it with println!("{:?}", sorted_boxes);.
Practice
(1/5)
1. What is the main idea behind the Counting Sort Algorithm?
easy
A. Compare each element with every other element to sort
B. Count the occurrences of each element and use counts to place elements in order
C. Divide the array into halves and sort recursively
D. Swap adjacent elements if they are in wrong order repeatedly
Solution
Step 1: Understand Counting Sort principle
Counting sort counts how many times each value appears in the input.
Step 2: Use counts to place elements
These counts help place elements directly in the sorted output without comparisons.
Final Answer:
Count the occurrences of each element and use counts to place elements in order -> Option B
Quick Check:
Counting sort = Counting occurrences and placing [OK]
Hint: Counting sort uses counts, not comparisons, to sort [OK]
Common Mistakes:
Thinking counting sort compares elements
Confusing counting sort with quicksort or mergesort
Assuming counting sort works on all data types
2. Which of the following is the correct Rust syntax to create a vector of zeros with length 5 for counting sort?
easy
A. let counts = vec![0; 5];
B. let counts = vec(0, 5);
C. let counts = [0; 5];
D. let counts = vec::new(5, 0);
Solution
Step 1: Recall Rust vector initialization
In Rust, vec![value; size] creates a vector with repeated values.
Step 2: Match syntax to create vector of zeros
vec![0; 5] creates a vector with five zeros, perfect for counting sort.
Final Answer:
let counts = vec![0; 5]; -> Option A
Quick Check:
vec![0; 5] creates vector of 5 zeros [OK]
Hint: Use vec![value; size] to create repeated elements vector [OK]
Common Mistakes:
Using parentheses instead of square brackets for vec!
Confusing array syntax with vector syntax
Trying to use vec::new with parameters
3. What will be the output of the following Rust code snippet implementing counting sort on array [4, 2, 2, 8, 3, 3, 1]?
fn counting_sort(arr: &[usize]) -> Vec<usize> {
let max = *arr.iter().max().unwrap();
let mut counts = vec![0; max + 1];
for &num in arr {
counts[num] += 1;
}
let mut sorted = Vec::new();
for (num, &count) in counts.iter().enumerate() {
for _ in 0..count {
sorted.push(num);
}
}
sorted
}
fn main() {
let arr = [4, 2, 2, 8, 3, 3, 1];
let sorted = counting_sort(&arr);
println!("{:?}", sorted);
}
Push each number count times in order: 1, 2, 2, 3, 3, 4, 8.
Final Answer:
[1, 2, 2, 3, 3, 4, 8] -> Option D
Quick Check:
Sorted array = [1, 2, 2, 3, 3, 4, 8] [OK]
Hint: Counting sort output is sorted array with repeated elements [OK]
Common Mistakes:
Forgetting to repeat elements by their count
Outputting original array instead of sorted
Miscounting occurrences of elements
4. Identify the bug in this Rust counting sort code snippet and choose the fix:
fn counting_sort(arr: &[usize]) -> Vec<usize> {
let max = arr.iter().max().unwrap();
let mut counts = vec![0; *max];
for &num in arr {
counts[num] += 1;
}
let mut sorted = Vec::new();
for (num, &count) in counts.iter().enumerate() {
for _ in 0..count {
sorted.push(num);
}
}
sorted
}
medium
A. Change let max = arr.iter().max().unwrap(); to let max = *arr.iter().max().unwrap();
B. Change for &num in arr to for num in arr.iter()
C. Change vec![0; *max] to vec![0; *max + 1]
D. Change sorted.push(num) to sorted.push(count)
Solution
Step 1: Check vector size for counts
Vector size is *max, but max element index is *max, so size must be *max + 1 to include max.
Step 2: Fix counts vector size
Changing to vec![0; *max + 1] prevents out-of-bound errors when counting max element.
Final Answer:
Change vec![0; *max] to vec![0; *max + 1] -> Option C
Quick Check:
Counts vector size = max + 1 [OK]
Hint: Counts vector must cover all indices up to max element [OK]
Common Mistakes:
Not adding +1 to vector size for max element
Dereferencing max incorrectly
Pushing count instead of element in sorted vector
5. You want to sort an array of integers that includes negative numbers using counting sort in Rust. Which approach correctly adapts counting sort for this case?
hard
A. Shift all numbers by adding the absolute value of the minimum negative number before counting
B. Use the original counting sort without changes; it works with negatives
C. Ignore negative numbers and sort only non-negative ones
D. Convert all numbers to positive by multiplying by -1 before sorting
Solution
Step 1: Understand counting sort limitation
Counting sort requires non-negative indices for counts, so negatives cause index errors.
Step 2: Shift numbers to non-negative range
Add absolute value of minimum negative number to all elements to shift them to zero or positive before counting.
Step 3: Sort and then shift back
After sorting, subtract the shift to restore original values in sorted order.
Final Answer:
Shift all numbers by adding the absolute value of the minimum negative number before counting -> Option A
Quick Check:
Shift negatives to non-negative before counting sort [OK]
Hint: Shift negatives to zero or positive before counting sort [OK]
Common Mistakes:
Trying to use counting sort directly on negatives
Ignoring negative numbers in input
Multiplying negatives by -1 changes order incorrectly
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.