sort_unstable_by_key Ranks Records By Field
Order records with sort_unstable_by_key using a cheap extracted key, and compare it with sort_by_key to see that unstable sorting does not preserve ties.
Code
#[derive(Debug, Clone)]
struct Job {
name: &'static str,
priority: u8,
}
fn main() {
let mut jobs = vec![
Job { name: "email", priority: 2 },
Job { name: "report", priority: 1 },
Job { name: "cleanup", priority: 2 },
Job { name: "billing", priority: 1 },
];
// unstable 版按 key 排序,不保证同 priority 的相对顺序
jobs.sort_unstable_by_key(|job| job.priority);
for job in &jobs {
println!("{}: priority {}", job.name, job.priority);
}
// 与 stable 版本对照:同 key 的输入顺序被保留
let mut stable = vec![
Job { name: "email", priority: 2 },
Job { name: "report", priority: 1 },
Job { name: "cleanup", priority: 2 },
Job { name: "billing", priority: 1 },
];
stable.sort_by_key(|job| job.priority);
println!("stable ties: {:?}", stable.iter().map(|j| j.name).collect::<Vec<_>>());
}What the code does
sort_unstable_by_key Ranks Records By Field comes down to the function main.
One loop does the cycling here: for job in &jobs.
Watch out for
- Self-contained — no imports beyond what the runtime already provides.
Applying it
The main signature reads fn main()
The file announces its steps in the output: stable ties:.
Statements that matter
jobs.sort_unstable_by_key(|job| job.priority);
stable.sort_by_key(|job| job.priority);
Interactive Tools for This Topic
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does sort_unstable_by_key Ranks Records By Field print when run?
- Execute the whole file; each printed line is prefixed with a label like `stable ties:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.