refactored sort function