Reputation: 11
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 }));
}
Upvotes: 1
Views: 84
Reputation: 7225
Your code is not skipping the for
loop. In your return
statement, you're returning -1
instead of the array's length
. This is why you're receiving -1
instead of 4
for your second test case { 90, 20, 40, 100 }
.
Your 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;
}
Upvotes: 2
Reputation: 41
You are testing a sorted array. For loop finishes itself and the return
within it 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;
}
Upvotes: 3
Reputation: 51
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;
}
}
Upvotes: 0
Reputation: 148
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,
Upvotes: 2