I’m looking for good study material about computation of weighted median algorithm and/or sample code in C++. The weights of my median are values between 0 and 1. Could you recommend me some links?
I’m looking for good study material about computation of weighted median algorithm and/or sample
Share
The weighted median is defined like so:
If
xis a sorted array ofNelements, andwis the array of weights with a total weightW, then the weighted median is the lastx[i]such that the sum ofw[i]and of all previous weights are less than or equal toS/2.In C++, this can be expressed like so (assuming
x,wandWare defined as above)EDIT
So it seems I answered this question too hastily and made some mistakes. I found a neat description of weighted median from the R documentation, which describes it like so:
From this description, we have a pretty straight-forward implementation of the algorithm. If we start with
k == 0, then there are no elements beforex[k], so the total weight of elementsx[i] < x[k]will be less thanS/2. Depending on the data, the total weight of the elementsx[i] > x[k]may or may not be less thanS/2. So we can just move forward through the array until this second sum becomes less than or equal toS/2:Note that if the median is the last element (
medianIndex == N-1), thensum == 0, so the conditionsum > S/2fails. Thus,kwill never be out of bounds (unlessN == 0!). Also, if there are two elements that satisfy the condition, the algorithm always selects the first one.