Select Nth Unstable Median
Find a median without sorting everything: select_nth_unstable partitions the slice in place and returns lower, middle, and higher parts.
Code
fn main() {
let mut samples = vec![42, 7, 19, 88, 3, 56, 71, 12, 30];
// select_nth_unstable partitions in place around the nth element
let middle = samples.len() / 2;
let (lower, median, higher) = samples.select_nth_unstable(middle);
println!("lower count: {}", lower.len());
println!("median: {median}");
println!("higher count: {}", higher.len());
// every lower value is <= the median and every higher value is >=
println!("partition holds: {}", lower.iter().all(|v| *v <= *median)
&& higher.iter().all(|v| *v >= *median));
// a full sort is only needed when every element must be ordered
samples.sort_unstable();
println!("sorted: {samples:?}");
let mut words = vec!["pear", "fig", "apple", "kiwi", "banana"];
let index = words.len() / 2;
let (_, word, _) = words.select_nth_unstable_by_key(index, |word| word.len());
println!("median by length: {}", *word);
}How it works
The snippet is organized around the function main.
What to watch for
- Nothing to vet in a supply-chain review — the file pulls in no packages.
Putting it to use
Signature: fn main()
Look for the lower count:, median:, higher count: prefixes when the file runs; they tie each line to its step.
Core lines
let (_, word, _) = words.select_nth_unstable_by_key(index, |word| word.len());
Interactive Tools for This Topic
FAQ
- What does Select Nth Unstable Median print when run?
- No setup needed: run the file and look for labeled lines like `lower count:`, `median:`, `higher count:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.