Modified sorting function