Refactored sorting to be re-usable