refactor sorting function