The for loop isn't correct (has to be i < nums.length
), also, your solution doesn't work if there is nothing to do:
final int[] expectedArray = {1,2,0,0};
final String expectedString = Arrays.toString(expectedArray);
int[] nothingToDo = {1,2,0,0};
moveZeroes(nothingToDo);
assertEquals(expectedString, Arrays.toString(nothingToDo));
yields in:
org.junit.ComparisonFailure: expected:<[[1, 2], 0, 0]> but was:<[[0, 0], 0, 0]>
Just write some test cases yourself and see what's wrong.
In your case:
if (j<nums.length){
nums[i]=nums[j];
nums[j]=0;
}
is wrong because you're swapping i
with j
, even if i == j
and nums[i] != 0
.
Since I don't think you're asking for a working solution, I won't provide one. But here are my test cases:
@Test
public void testEmptyArray() {
int[] array = new int[0];
moveZeroes(array);
assertEquals(0,array.length);
}
@Test
public void testZeroOnlyArrays() {
int[] array = {0,0,0,0};
final String arrayString = Arrays.toString(array);
moveZeroes(array);
assertEquals(arrayString, Arrays.toString(array));;
}
@Test
public void mixedTest() {
int[] array = {0,1,0,2};
final int[] expectedArray = {1,2,0,0};
final String expectedString = Arrays.toString(expectedArray);
moveZeroes(array);
assertEquals(expectedString, Arrays.toString(array));;
int[] nothingToDo = {1,2,0,0};
moveZeroes(nothingToDo);
assertEquals(expectedString, Arrays.toString(nothingToDo));
}