Modified code to correct sorting issue