Given a list of tuples representing (name, score), what is the output after applying a stable sort by score?
let mut data = vec![
("Alice", 90),
("Bob", 85),
("Charlie", 90),
("Dave", 85),
];
data.sort_by_key(|k| k.1);
println!("{:?}", data);Stable sort keeps the original order of equal elements.
Rust's sort_by_key is stable, so elements with the same score keep their original order.
Choose the best reason to use a stable sort instead of an unstable sort.
Think about what 'stable' means in sorting.
Stable sorting keeps equal elements in their original order, which is important when that order carries meaning.
Consider this Rust code using sort_unstable_by with a comparator that violates strict ordering rules. What happens?
let mut nums = vec![3, 1, 2]; nums.sort_unstable_by(|a, b| { if *a == 2 && *b == 3 { std::cmp::Ordering::Less } else if *a == 3 && *b == 2 { std::cmp::Ordering::Greater } else { a.cmp(b) } }); println!("{:?}", nums);
Think about what happens if the comparator is not consistent.
An inconsistent comparator breaks sorting assumptions, causing sort_unstable_by to panic at runtime.
You have a large list that is almost sorted except for a few elements. Which sorting algorithm is most efficient to use?
Consider which algorithm benefits from partial order.
Insertion sort is efficient for nearly sorted data as it only moves misplaced elements.
Choose the best explanation for preferring an unstable sort over a stable sort.
Think about trade-offs between speed and stability.
Unstable sorts can be faster and use less memory but do not preserve order of equal elements.
