Updated sorting algorithm