implemented sorting function