Skip to content

Add "nth_element" function for [T] #1470

Closed
@Mokosha

Description

@Mokosha

Apologies if this has been brought up before -- a cursory search with google brought up nothing.

Analogous to the std::nth_element function in C++, Rust slices should be able to do a partial quicksort to just get to the nth smallest element. I believe that this is fairly straightforward and analogous to the C++ implementation, and people have already mentioned it a few times. I suspect the function signatures would look something like this:

impl<T> [T] {
  fn nth_element(&mut self, n: usize) where T : Ord;
  fn nth_element_by<F>(&mut self, n: usize, f: F) where F: FnMut(&T, &T) -> Ordering;
}

I think the name nth_element is a bit clunky though, so perhaps sort_at_element would be better? In particular, I've linked the paper used in most C++ implementations for the introsort algorithm.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-libs-apiRelevant to the library API team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions