Tweaked implementation of median (fixes #7331)