Let\'s say I need to retrieve the median from a sequence of 1000000 random numeric values.
If using anything but std::list
, I have no (
Here's a more complete version of Mike Seymour's answer:
// Could use pass by copy to avoid changing vector
double median(std::vector &v)
{
size_t n = v.size() / 2;
std::nth_element(v.begin(), v.begin()+n, v.end());
int vn = v[n];
if(v.size()%2 == 1)
{
return vn;
}else
{
std::nth_element(v.begin(), v.begin()+n-1, v.end());
return 0.5*(vn+v[n-1]);
}
}
It handles odd- or even-length input.