Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
C++ - Java Median
// Compute the median with std::nth_element
template<class T>
T vtkComputeMedianOfArray(T *aBegin, T *aEnd)
{
T *aMid = aBegin + (aEnd - aBegin)/2;
std::nth_element(aBegin, aMid, aEnd);
T m = *aMid;
// if even size, get max of lower part of array and compute the average
if (aMid - aBegin == aEnd - aMid)
{
T *lowMid = std::max_element(aBegin, aMid);
m = *lowMid + (m - *lowMid)/2;
}
return m;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment