Completed function sorting algorithm