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
lazysortcrate is exactly what you need:This code allows us to see that
lazysortis faster than the solution withBinaryHeap. We can also see thatBinaryHeapsolution gets worse whenNincreases.The problem with
lazysortis 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
Nis aboutSIZE_VEC / 3, the classicsortwins.You could submit an RFC/issue to ask about adding this feature to the standard library.