Sorting Stability and When to Use Which Sort in DSA Rust - Time & Space Complexity
Sorting is a common task where we arrange items in order. Knowing how long different sorting methods take helps us pick the best one.
We want to understand how the time to sort grows as the list gets bigger and when to choose each sort.
Analyze the time complexity of the following sorting code snippets.
// Bubble Sort (stable)
fn bubble_sort(arr: &mut [i32]) {
let n = arr.len();
for i in 0..n {
for j in 0..n - i - 1 {
if arr[j] > arr[j + 1] {
arr.swap(j, j + 1);
}
}
}
}
// Quick Sort (unstable)
fn quick_sort(arr: &mut [i32]) {
if arr.len() <= 1 { return; }
let pivot = arr[arr.len() / 2];
let (mut left, mut right) = (0, arr.len() - 1);
while left <= right {
while arr[left] < pivot { left += 1; }
while arr[right] > pivot { right -= 1; }
if left <= right {
arr.swap(left, right);
left += 1;
if right > 0 { right -= 1; }
}
}
if right > 0 {
quick_sort(&mut arr[0..=right]);
}
quick_sort(&mut arr[left..]);
}
These snippets show two common sorts: Bubble Sort which keeps equal items in order, and Quick Sort which is faster but may reorder equal items.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Bubble Sort uses nested loops to compare and swap adjacent items repeatedly. Quick Sort uses recursion and partitioning loops.
- How many times: Bubble Sort compares pairs roughly n×(n-1)/2 times. Quick Sort partitions and recurses about log n times on average.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Bubble: ~45, Quick: ~30 |
| 100 | Bubble: ~4,950, Quick: ~664 |
| 1000 | Bubble: ~499,500, Quick: ~9,966 |
Pattern observation: Bubble Sort operations grow very fast as n increases (square growth), while Quick Sort grows much slower (n log n growth).
Time Complexity: O(n²) for Bubble Sort, O(n log n) average for Quick Sort
Bubble Sort takes much longer as the list grows, while Quick Sort is faster but may reorder equal items.
[X] Wrong: "Faster sorting always means stable sorting."
[OK] Correct: Some fast sorts like Quick Sort can change the order of equal items, which matters when stability is needed.
Understanding sorting time helps you choose the right method for your data and needs. Stability matters when order of equal items is important, and speed matters when data is large.
"What if we used Merge Sort instead? How would the time complexity and stability change?"
Practice
stable?Solution
Step 1: Understand stability in sorting
A stable sort means if two elements are equal, their order stays the same as before sorting.Step 2: Compare options with definition
Only It keeps the original order of equal elements unchanged matches this meaning. Other options describe unrelated properties.Final Answer:
It keeps the original order of equal elements unchanged -> Option DQuick Check:
Stable sort = keeps equal elements order [OK]
- Confusing stability with sorting order
- Thinking stability means faster sorting
- Assuming stability means less memory use
Solution
Step 1: Recall Rust slice sorting methods
Rust'sslice.sort()uses a stable sorting algorithm.Step 2: Differentiate stable and unstable methods
sort_unstable()andsort_unstable_by()are unstable sorts.sort_by()is stable but requires a comparator.Final Answer:
slice.sort()-> Option CQuick Check:
slice.sort()= stable sort [OK]
sort() for stable sorting in Rust [OK]- Choosing
sort_unstable()thinking it's stable - Confusing
sort_by()with unstable sort - Not knowing
sort()is stable by default
let mut data = [(3, 'a'), (1, 'b'), (3, 'c'), (2, 'd')];
data.sort();
println!("{:?}", data);Solution
Step 1: Understand sorting of tuples in Rust
Rust sorts tuples by first element, then second if first are equal. Here, sorting by integer first.Step 2: Apply stable sort to keep order of equal keys
Elements with key 3 are (3, 'a') then (3, 'c'). Stable sort keeps this order.Final Answer:
[(1, 'b'), (2, 'd'), (3, 'a'), (3, 'c')] -> Option AQuick Check:
Stable sort keeps (3, 'a') before (3, 'c') [OK]
- Swapping order of equal keys
- Ignoring tuple sorting rules
- Assuming unstable sort by default
sort_unstable() but the order of equal elements is important. What is the main issue?
let mut items = [(2, 'x'), (1, 'y'), (2, 'z')];
items.sort_unstable();
println!("{:?}", items);Solution
Step 1: Understand
sort_unstable()behaviorsort_unstable()sorts faster but does not guarantee stable order of equal elements.Step 2: Identify problem with equal keys
Elements with key 2 may swap order, so (2, 'x') and (2, 'z') order can change, which breaks stability.Final Answer:
The order of (2, 'x') and (2, 'z') may change, breaking stability -> Option BQuick Check:
Unstable sort = order of equal keys can change [OK]
- Thinking unstable sort always panics
- Assuming unstable sort requires comparator
- Believing unstable sort keeps order
(score: i32, name: &str). You want to sort by score ascending but keep the original order of students with the same score. Which sorting method should you use in Rust and why?Solution
Step 1: Identify requirement for stability
We want to keep original order of students with same score, so stable sort is needed.Step 2: Choose Rust method that is stable
sort()is stable and sorts ascending by default.sort_unstable()is faster but unstable.sort_unstable_by()is unstable even with comparator.sort_by()is stable but Usesort_by()but it is unstable so order may change claims it is unstable incorrectly.Final Answer:
Usesort()because it is stable and preserves order of equal scores -> Option AQuick Check:
Stable sort needed = usesort()[OK]
sort() [OK]- Choosing unstable sort for speed ignoring order
- Thinking
sort_unstable_by()is stable - Misunderstanding
sort_by()stability
Ready to prove it?
Pass the test and this pattern moves unknown
