Updated sorting to take ties into consideration