Consider the following function, median:
real_t median(const std::initializer_list<real_t> vars) {
real_t tmp[15];
const unsigned x = vars.size() / 2;
if (x & 1) {
std::partial_sort_copy(vars.begin(), vars.end(), &tmp[0], &tmp[x]);
return tmp[x];
}
const unsigned y = x + 1;
std::partial_sort_copy(vars.begin(), vars.end(), &tmp[0], &tmp[y]);
return (tmp[x] + tmp[y]) / 2;
}
I am using a partial sort to decrease complexity, as I only need to sort half of the list.
Further, I have assumed that std::partial_sort_copy is faster than std::partial_sort or std::nth_element because there is no shuffling required in the sort algorithm (It1 != It2). Is my assumption correct?
NB: Assume real_t could be a double, so please don't criticise the use of division.
NBB: I'm using -pedantic and vars is known to not be longer than 15 elements.