build median function