Improved the problematic internal sort function