Keep each weight attached to its value while sorting, then return the first cumulative weight reaching one half:
weightedMedian(A, weights):
R = records (A[i], weights[i], i), sorted by first component
cumulative = 0
for (value, weight, original_index) in R:
cumulative = cumulative + weight
if cumulative >= 1/2:
return original_indexAll weights are positive, so the cumulative weights strictly increase. At the returned entry the mass strictly to its left is below one half, while the mass strictly to its right is at most one half. This is the lower weighted median, including the exact equality case: stop at the earlier value whose cumulative mass is exactly one half. Sorting takes and the scan takes , giving time.
Weighted median Created 2026-10-20 Updated 2026-10-31
A median of a weighted probability distribution. With positive weights summing to one, at most half the weight lies strictly below a weighted median and at most half lies strictly above it. The lower weighted median chooses the first observed value whose cumulative weight reaches one half; the convention matters when the cumulative mass is exactly one half.