corrected sorting algorithm