I wish to compute the median value from an array of floats in C++:
float Median( FloatArray const * constFloatArray )
{
FloatArray scratch = FloatArray( *constFloatArray );
int64_t const size = scratch.GetWidth() * scratch.GetHeight();
int64_t const mid = size / 2;
std::nth_element( scratch.begin(), scratch.begin() + mid, scratch.end() );
return scratch[ mid ];
}
The FloatArray contains a regular C++ array of floats.
I'm using std::nth_element
but wonder if there is a facility like nth_element
that works with const
data? Right now, I'm making a copy and then doing nth_element
before throwing the copy away. If there isn't something like nth_element
for const
data, is there a more efficient approach that uses the copy step to compute information and thus avoid a potentially additional O(n) loop? Perhaps the performance impact would be negligible? My array size could be on the order of 2 billion.