Fix crash in sorting function