Refactor sort function