finished median function