0

When solving a cycle sort problem, I was getting an index error. When I checked the solution, the only error was the order in which I wrote conditions within an if statement.

This worked

    if nums[i] > 0 and nums[i] <= n and nums[i] != nums[j]:
      nums[i], nums[j] = nums[j], nums[i]

This did not

    if nums[i] > 0 and nums[i] != nums[j] and nums[i] <= n:
      nums[i], nums[j] = nums[j], nums[i]

I tried to google but am not understanding why one would work and not the other. It only jumps into the if statement if all are correct, so why would order matter?

I would expect both to do the same. When jumping into the if statement, why would it matter if the second one failed or the third? Either way it should jump into the else statement.

0 Answers0