Generalized the sorting algo