Refactored sorting into function