Vec Swap Reorders By Index
Reorder elements in place with Vec::swap by index, then run selection-sort's opening move by finding the minimum with min_by and swapping it to front.
Code
fn main() {
let mut order = vec!["beta", "delta", "alpha", "gamma"];
// swap reorders two elements in place by index, no temporary needed
order.swap(0, 2);
println!("{order:?}");
// 选择排序第一步:把最小值换到开头
let mut scores = vec![83, 41, 97, 12, 60];
let (min_index, _) = scores
.iter()
.enumerate()
.min_by(|a, b| a.1.cmp(b.1))
.unwrap();
scores.swap(0, min_index);
println!("min moved to front: {scores:?}");
}Vec Swap Reorders By Index: reading the source
Every interesting line belongs to main.
Points of care
- Copy, run: the standard library answers every call in the file.
Applying it
Signature: fn main()
The demo output is labeled (min moved to front:), so attributing each line to its operation is immediate.
Statements that matter
.min_by(|a, b| a.1.cmp(b.1))
.unwrap();
Interactive Tools for This Topic
FAQ
- What does Vec Swap Reorders By Index print when run?
- Execute the whole file; each printed line is prefixed with a label like `min moved to front:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.