Refactored sorting