Using std nth element To Find The Median Or Other Quantiles
suggest changeThe std::nth_element algorithm takes three iterators: an iterator to the beginning, nth position, and end. Once the function returns, the nth element (by order) will be the nth smallest element. (The function has more elaborate overloads, e.g., some taking comparison functors; see the above link for all the variations.)
Note On average this function has linear complexity. The standard does not require the worst case to be linear.
For the sake of this example, the median is the element placed at zero-based index n / 2. For length 5 that is index 2, the 3rd smallest element. For length 6 it is index 3, the 4th smallest. That is not the same as 1-based position ⌈n / 2⌉, which would be the 3rd smallest for both lengths.
To use this function to find the median, we can use the following. Say we start with
std::vector<int> v{5, 1, 2, 3, 4};
std::vector<int>::iterator b = v.begin();
std::vector<int>::iterator e = v.end();
std::vector<int>::iterator med = b;
std::advance(med, v.size() / 2);
// Index 2 receives the element that would sit there in sorted order.
std::nth_element(b, med, e);
// The median is now at v[2], the 3rd smallest.
To find the pth quantile, take p as a fraction from 0 to 1 and replace the advance above. The product is truncated when stored in std::size_t.
const std::size_t pos = p * std::distance(b, e);
std::advance(med, pos);
and look for the quantile at position pos.