improved sorting function