fixed the function to be based on sorting