fixed the check for sorted