Implemented sorting function