Should be i<n-1, since the last swap with i=n-1 switches the last element with itself.