Refactor the sorting code