refactored sort method