Used sortperm in weighted median to improve speed and memory use