Code refactoring: sort function