Fastest code C/C++ to select the median in a set of 27 floating point values

The selection algorithm is linear time (O(n)). Complexity-wise you can’t do better than linear time, because it takes linear time to read in all the data. So you couldn’t have made something that is faster complexity-wise. Perhaps you have something that is a constant factor faster on certain inputs? I doubt it would make much of a difference.

C++ already includes the linear-time selection algorithm. Why not just use it?

std::vector<YourType>::iterator first = yourContainer.begin();
std::vector<YourType>::iterator last = yourContainer.end();
std::vector<YourType>::iterator middle = first + (last - first) / 2;
std::nth_element(first, middle, last); // can specify comparator as optional 4th arg
YourType median = *middle;

Edit: Technically, that is only the median for a container of odd length. For one of even length, it will get the “upper” median. If you want the traditional definition of median for even length, you might have to run it twice, once for each of the two “middles” at first + (last - first) / 2 and first + (last - first) / 2 - 1 and then average them or something.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)