Home > Enterprise >  Java function not returning expected output
Java function not returning expected output

Time:05-08

I have this function below its intended purpose is to return the first index where data isn't sorted in ascending order. If the data is sorted, it will just return the length of the array. For example {10, 20, 90, 5, 70} would return 3 (90 > 5). If any of the data is null or invalid it just returns -1. Currently, the function is expecting 4 to be returned but it skips over the loops and returns -1 instead of 4. Any tips to help would be appreciated.

    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;
}

Test cases:

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 }));
}

CodePudding user response:

Your code has some flaws. if you want to return the array length if the array is sorted in ascending order then you need to fix your last return statement.

The fixed code should look like this:

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 data.length;
}

CodePudding user response:

You are testing sorted array. For loop finishes itself and "return" inside is never called. Last return before end of the function should be return data.length;

public static int partSorted(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 data.length;
}

CodePudding user response:

The reason is, for a sorted array, you pass the for loop without returning a value, then, you return -1 with your last statement. Therefore, just change return -1 to return data.length in your last statement,

CodePudding user response:

Try this

    public static int Sorted(int[] data) {
    if (data == null)
        return -1;
    int parSorCount = 1;
    for (int i = 1; i < data.length; i  ) {
        if (data[i - 1] <= data[i]) {
            parSorCount  ;
        } else {
            break;
        }
    }
    if (parSorCount < 2) {
        return 1;
    } else {
        return parSorCount;
    }
}
  •  Tags:  
  • java
  • Related