To handle the "no swap" situation, here is my proposal:
When entering the outer loop, save the value of
i
in a temporary variable and set
i
to
length - 1
(this value will cause an exit at the next iteration). And in the body of the if test (i.e. when a swap is made), restore the value of
i
.
Loop on i:
Save i
Set i to exit value
Loop on j:
if Out-of-order
Swap
Restore i
Beware that this is a non-classical solution, your teacher will be intrigued.