refactored sort