Skip to content

Instantly share code, notes, and snippets.

@sebastianhaas
Created January 4, 2016 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebastianhaas/5662ce6a8ba1dfb3a1e0 to your computer and use it in GitHub Desktop.
Save sebastianhaas/5662ce6a8ba1dfb3a1e0 to your computer and use it in GitHub Desktop.
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