Fastest way of finding the middle value of a triple?

There’s an answer here using min/max and no branches (https://stackoverflow.com/a/14676309/2233603). Actually 4 min/max operations are enough to find the median, there’s no need for xor’s: median = max(min(a,b), min(max(a,b),c)); Though, it won’t give you the median value’s index… Breakdown of all cases: a b c 1 2 3 max(min(1,2), min(max(1,2),3)) = max(1, min(2,3)) = max(1, … Read more

What is the right approach when using STL container for median calculation?

Any random-access container (like std::vector) can be sorted with the standard std::sort algorithm, available in the <algorithm> header. For finding the median, it would be quicker to use std::nth_element; this does enough of a sort to put one chosen element in the correct position, but doesn’t completely sort the container. So you could find the … Read more

Rolling median algorithm in C

I have looked at R’s src/library/stats/src/Trunmed.c a few times as I wanted something similar too in a standalone C++ class / C subroutine. Note that this are actually two implementations in one, see src/library/stats/man/runmed.Rd (the source of the help file) which says \details{ Apart from the end values, the result \code{y = runmed(x, k)} simply … Read more

Calculate median in c#

Looks like other answers are using sorting. That’s not optimal from performance point of view because it takes O(n logn) time. It is possible to calculate median in O(n) time instead. The generalized version of this problem is known as “n-order statistics” which means finding an element K in a set such that we have … Read more

Calculating median – javascript

Change your median method to this: function median(values){ if(values.length ===0) throw new Error(“No inputs”); values.sort(function(a,b){ return a-b; }); var half = Math.floor(values.length / 2); if (values.length % 2) return values[half]; return (values[half – 1] + values[half]) / 2.0; } fiddle