Skip to content
Snippets Groups Projects
Unverified Commit 5f74630d authored by Shaun Wang's avatar Shaun Wang Committed by GitHub
Browse files

Use 'select_nth_unstable' to get median. (#467)

* Use 'select_nth_unstable' to get median.

* fix

* Update comments doc.
parent ffe1601f
No related branches found
No related tags found
No related merge requests found
......@@ -27,13 +27,13 @@ where
let count = values.len() as u32;
let minimum_count = MinimumCount::get();
if count < minimum_count {
if count < minimum_count || count == 0 {
return prev_value;
}
values.sort_by(|a, b| a.value.cmp(&b.value));
let median_index = count / 2;
Some(values[median_index as usize].clone())
let mid_index = count / 2;
// Won't panic as `values` ensured not empty.
let (_, value, _) = values.select_nth_unstable_by(mid_index as usize, |a, b| a.value.cmp(&b.value));
Some(value.clone())
}
}
......@@ -30,10 +30,9 @@ pub fn median<T: Ord + Clone>(mut items: Vec<T>) -> Option<T> {
let mid_index = items.len() / 2;
items.sort();
// Won't panic as guarded items not empty case.
Some(items[mid_index as usize].clone())
// Won't panic as `items` ensured not empty.
let (_, item, _) = items.select_nth_unstable(mid_index);
Some(item.clone())
}
#[macro_export]
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment