Search code examples
c++algorithmmedian

What's the most efficient way to extract min, max & median from a vector


Given a vector<T> vec{...} what's the best way to extract its minimum, maximum and median assuming T is one of the numeric types? I know of std::nth_element as well as std::minmax_element but they seem to do redundant work if called one after another.

The best idea I came up with so far is to just call std::nth_element 3 times one after another. But this still needs 3N comparisons, right? Is there any way to reuse the partial sorting done in previous iterations?


Solution

  • Use std::nth_element to partition which yields the median, then std::min_element in the left half and std::max_element in the right one.

    If you need it to be faster than that then roll your own version based on std::nth_element.