What if you could sort thousands of items instantly without comparing each one?
Why Counting Sort Algorithm in DSA Rust?
Imagine you have a big box of colored balls mixed up, and you want to arrange them by color quickly. Doing it by picking one ball at a time and comparing it with others is tiring and slow.
Sorting by comparing each ball with every other ball takes a lot of time and effort, especially when there are many balls. It's easy to make mistakes and lose track.
Counting Sort counts how many balls of each color there are first, then places them in order without comparing each ball to others. This makes sorting fast and simple.
fn manual_sort(arr: &mut [u32]) {
for i in 0..arr.len() {
for j in i+1..arr.len() {
if arr[i] > arr[j] {
arr.swap(i, j);
}
}
}
}fn counting_sort(arr: &mut [u32]) {
let max_value = *arr.iter().max().unwrap_or(&0);
let mut count = vec![0; (max_value + 1) as usize];
for &num in arr.iter() {
count[num as usize] += 1;
}
let mut index = 0;
for num in 0..=max_value as usize {
for _ in 0..count[num] {
arr[index] = num as u32;
index += 1;
}
}
}Counting Sort enables lightning-fast sorting when you know the range of values, making big sorting tasks easy and error-free.
Sorting exam scores from 0 to 100 for thousands of students quickly to find top performers without comparing each score to every other.
Manual comparison sorting is slow and error-prone for large data.
Counting Sort counts occurrences to sort efficiently without comparisons.
Best used when data values have a known, limited range.
Practice
Counting Sort Algorithm?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 BQuick Check:
Counting sort = Counting occurrences and placing [OK]
- Thinking counting sort compares elements
- Confusing counting sort with quicksort or mergesort
- Assuming counting sort works on all data types
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 AQuick Check:
vec![0; 5] creates vector of 5 zeros [OK]
- Using parentheses instead of square brackets for vec!
- Confusing array syntax with vector syntax
- Trying to use vec::new with parameters
[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);
}Solution
Step 1: Count occurrences of each number
Input array: [4, 2, 2, 8, 3, 3, 1]. Counts: 1->1, 2->2, 3->2, 4->1, 8->1.Step 2: Build sorted vector using counts
Push each number count times in order: 1, 2, 2, 3, 3, 4, 8.Final Answer:
[1, 2, 2, 3, 3, 4, 8] -> Option DQuick Check:
Sorted array = [1, 2, 2, 3, 3, 4, 8] [OK]
- Forgetting to repeat elements by their count
- Outputting original array instead of sorted
- Miscounting occurrences of elements
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
}Solution
Step 1: Check vector size for counts
Vector size is*max, but max element index is*max, so size must be*max + 1to include max.Step 2: Fix counts vector size
Changing tovec![0; *max + 1]prevents out-of-bound errors when counting max element.Final Answer:
Changevec![0; *max]tovec![0; *max + 1]-> Option CQuick Check:
Counts vector size = max + 1 [OK]
- Not adding +1 to vector size for max element
- Dereferencing max incorrectly
- Pushing count instead of element in sorted vector
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 AQuick Check:
Shift negatives to non-negative before counting sort [OK]
- Trying to use counting sort directly on negatives
- Ignoring negative numbers in input
- Multiplying negatives by -1 changes order incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
