Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to sort the vector in ascending order using a stable sort.
DSA Rust
let mut numbers = vec![3, 1, 4, 1, 5]; numbers.[1]();
Attempts:
3 left
💡 Hint
Common Mistakes
Using `sort_unstable()` which is not stable.
Using methods that do not sort like `reverse()` or `shuffle()`.
✗ Incorrect
The `sort()` method in Rust performs a stable sort, preserving the order of equal elements.
2fill in blank
mediumComplete the code to sort a vector of tuples by the second element using a stable sort.
DSA Rust
let mut pairs = vec![(1, 3), (2, 1), (3, 3)]; pairs.sort_by_key(|k| k.[1]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using index 0 which sorts by the first element.
Using an index out of range like 2 or 3.
✗ Incorrect
Index 1 accesses the second element of the tuple, which is used as the key for sorting.
3fill in blank
hardFix the error in the code to perform an unstable sort on the vector.
DSA Rust
let mut data = vec![5, 3, 8, 1]; data.[1]();
Attempts:
3 left
💡 Hint
Common Mistakes
Using `sort()` which is stable, not unstable.
Using `sort_by` or `sort_by_key` without unstable suffix.
✗ Incorrect
The `sort_unstable()` method performs an unstable sort which is faster but does not preserve order of equal elements.
4fill in blank
hardFill both blanks to sort a vector of strings by length using a stable sort.
DSA Rust
let mut words = vec!["apple", "bat", "carrot"]; words.sort_by_key(|word| word.[1]()); // This sort is [2]
Attempts:
3 left
💡 Hint
Common Mistakes
Using `length()` which does not exist in Rust strings.
Saying the sort is unstable when it is stable.
✗ Incorrect
The `len()` method returns the length of a string slice. The `sort_by_key` method is stable.
5fill in blank
hardFill all three blanks to create a vector of tuples sorted by the second element in descending order using an unstable sort.
DSA Rust
let mut items = vec![("a", 2), ("b", 3), ("c", 1)]; items.sort_unstable_by(|a, b| b.[1].cmp(&a.[2])); // The sort is [3]
Attempts:
3 left
💡 Hint
Common Mistakes
Using index 0 which accesses the first element.
Saying the sort is stable when it is unstable.
✗ Incorrect
Index 1 accesses the second element of the tuple. Using `sort_unstable_by` makes the sort unstable.
