Refactor sorting