Created
January 4, 2016 17:20
-
-
Save sebastianhaas/5662ce6a8ba1dfb3a1e0 to your computer and use it in GitHub Desktop.
C++ - Java Median
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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