Corrected bug in sort function