Corrected sorting function.