# Weighted median

The top chart shows a list of elements with values indicated by height and the median element shown in red. The lower chart shows the same elements with weights as indicated by the width of the boxes. The weighted median is shown in red and is different than the ordinary median.

In statistics, a weighted median of a sample is the 50% weighted percentile.[1][2][3] It was first proposed by F. Y. Edgeworth in 1888.[4][5] Like the median, it is useful as an estimator of central tendency, robust against outliers. It allows for non-uniform statistical weights related to, e.g., varying precision measurements in the sample.

## Properties

Weighted median of a set partitions that set in two halves such that sum of weights in each partition is as equal as possible.

If weights of all numbers in the set are equal then median is same as weighted median.

When set has even number of elements, we will have lower weighted median and upper weighted median instead of a single element as median.

## Example

Consider the set of numbers $\{0.1; 0.35; 0.05; 0.1; 0.15; 0.05; 0.2\}$ with each number having weights $1, 2, 3, 4, 5, 6, 7$ respectively. The median is 0.1 and the weighted median is 0.2.

## Algorithm

Weighted median can be computed by sorting the set of numbers and finding the smallest numbers which sums to half the weight of total weight. This algorithm takes $O(n \log n)$ time. There is more optimal approach to find weighted median as using modified selection algorithm.[1]

```//Main call is WeightedMedian(a, 1, n)
//Returns lower median
WeightedMedian(a[1..n], p, r)
//base case for single element
if r = p
return a[p]
//base case for two elements
//make sure we return lower median
if r-p = 1
if a[p].w >= a[r].w
return a[p]
else return a[r]
//partition around pivot r
q = partition(a, p, r)
wl, wg = sum weights of partitions (p, q-1), (q+1, r)
//if partitions are balanced then we are done
if wl and wg both < 1/2
return a[q]
else
//increase pivot weight by the amount of partition we eliminate
if wl > wg
a[q].w += wg
//recurse on pivot inclusively
WeightedMedian(a, p, q)
else
a[q].w += wl
WeightedMedian(a, q, r)
```

As the recursive call in inclusive of median, recurrence relation is,

$T(n) = T(n/2 + 1) + O(n)$

Which yields $O(n)$ runtime.