0

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.

  • 1
    With `for (int i = 0; i < data.length; i++) { if (data[i + 1] < data[i])`, `i+1` is outside of the array for the iteration of your loop (because it will be equal to `data.length` and the last valid index in your array is `data.length - 1`) – knittl May 07 '22 at 15:18

2 Answers2

1

When "i" reaches last index, "i+1" is out of array length. Try this one:

public static int Sorted(int[] data) {
    if (data == null)
        return -1;
    for (int i = 0; i < data.length - 1; i++) {
        if (data[i + 1] < data[i])
            return (i + 1);
    }
    return -1;
}
0

In java, the indexes for n-length array are {0,...n-1}.

In your if statement if (data[i + 1] < data[i]) , you exceed this n-1.

The reason is the following: For i variable, you iterate {0,...,n-1} which means, for i+1, you iterate {1,...,n}. When you try to access data[i + 1] for i+ 1 = n, you get out of the indexes and the computer says: Hey, there is no n-th element!

To summarize, you should not compare the last(n-1 th) element with n-th(that does not exist) element. You should iterate your i for {0,...,n-2}.

Therefore, you should change your for loop as:

for (int i = 0; i < data.length - 1; i++) {
        if (data[i + 1] < data[i])
            return (i + 1);
}
wolfenblut
  • 131
  • 1
  • 11