Refactor sort_and_merge