I need to get the top N items from a Vec
which is quite large in production. Currently I do it like this inefficient way:
let mut v = vec![6, 4, 3, 7, 2, 1, 5];
v.sort_unstable();
v = v[0..3].to_vec();
In C++, I'd use std::partial_sort
, but I can't find an equivalent in the Rust docs.
Am I just overlooking it, or does it not exist (yet)?
The standard library doesn't contain this functionality, but it looks like the
lazysort
crate is exactly what you need:This code allows us to see that
lazysort
is faster than the solution withBinaryHeap
. We can also see thatBinaryHeap
solution gets worse whenN
increases.The problem with
lazysort
is that it creates a secondVec<_>
. A "better" solution would be to implement the partial sort in-place. I provided an example of such an implementation.Keep in mind that all these solutions come with overhead. When
N
is aboutSIZE_VEC / 3
, the classicsort
wins.You could submit an RFC/issue to ask about adding this feature to the standard library.