Bug fixes to sorting algorithm