Currently, I am getting an error for the following code. The error is Index 4 is out of bounds for length 4. Essentially what I am trying to do is return the first index of where data isn't sorted in ascending order. If the data is sorted the function returns the length of the array. An example being For example {10, 20, 90, 5, 70} would return 3 (90 > 5). Then if data is invalid it returns -1.
public static int Sorted(int[] data) {
if (data == null)
return -1;
for (int i = 0; i < data.length; i++) {
if (data[i + 1] < data[i])
return (i + 1);
}
return -1;
}
The test cases I am using are here below:
@Test
public void testSorted() {
assertEquals(-1, Stage1.partSorted(null));
assertEquals(1, Stage1.partSorted(new int[] { 90, 20, 40, 100 }));
assertEquals(4, Stage1.partSorted(new int[] { 10, 20, 40, 100 }));
assertEquals(3, Stage1.partSorted(new int[] { 10, 20, 90, 70 }));
assertEquals(4, Stage1.partSorted(new int[] { 20, 20, 30, 40, 5, 70, 90, 80 }));
Any help or clues would be appreciated.