refactoring in sorting logic