-
Notifications
You must be signed in to change notification settings - Fork 24
Description
Proposal
Problem statement
[T] now has:
sortsort_bysort_unstablesort_unstable_by
In my scenario to implement a "Top-N" algorithm over slices, it'd be better to have a partial_sort analogy to the sort family.
See the alternative and links for the existing workaround and discussions.
Motivating examples or use cases
impl<T> [T] {
// `n` is the length of the sorted slice
pub fn partial_sort(&mut self, n: usize) where T: Ord { ... }
pub fn partial_sort_by<F>(&mut self, n: usize, mut compare: F) where F: FnMut(&T, &T) -> Ordering { ... }
pub fn partial_sort_unstable(&mut self, n: usize) where T: Ord { ... }
pub fn partial_sort_unstable_by<F>(&mut self, n: usize, mut compare: F) where F: FnMut(&T, &T) -> Ordering { ... }
}
#[test]
fn demostration() {
let mut before: Vec<u32> = vec![4, 4, 3, 3, 1, 1, 2, 2];
let last = 6;
let mut d = before.clone();
d.sort();
before.partial_sort_by(last, |a, b| a.cmp(b));
assert_eq!(&d[0..last], &before[0..last]);
}Solution sketch
arrow-ord provides an implementation:
/// It's unstable_sort, may not preserve the order of equal elements
pub fn partial_sort<T, F>(v: &mut [T], limit: usize, mut is_less: F)
where
F: FnMut(&T, &T) -> Ordering,
{
if let Some(n) = limit.checked_sub(1) {
let (before, _mid, _after) = v.select_nth_unstable_by(n, &mut is_less);
before.sort_unstable_by(is_less);
}
}We can start from here and further internal improvement.
Alternatives
There is an existing crate for partial_sort: https://github.com/sundy-li/partial_sort
... and I'm currently using it in ScopeDB, where it works well.
Links and related work
What happens now?
This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.
Possible responses
The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):
- We think this problem seems worth solving, and the standard library might be the right place to solve it.
- We think that this probably doesn't belong in the standard library.
Second, if there's a concrete solution:
- We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
- We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.