improved sort function