dmetal23 dmetal23 - 7 months ago 17
Java Question

Checking an array for descending order

I am writing code to check if my array is in ascending or descending order. If the boolean 'ascending' is true, then I check if it is ascending. If it is false, then I check for descending. I need help checking whether the array is descending or not... I have the code to check ascending which is written below:

protected boolean isSorted(boolean ascending) {
boolean result = false;

if (ascending) {
for (int i=0;i<data.length-1;i++) {
if(data[i] < data[i+1]) {
result = true;
} else if(data[i] > data[i+1]) {
result = false;
}
}
} else {
//code to check for descending order
}
}

Answer

The first part of the if (the "ascending" check) is wrong, it should be:

for (int i = 0; i < data.length-1; i++) {
    if (data[i] > data[i+1]) {
        return false;
    }
}
return true;

Conversely, the descending check should be (and notice that it's enough to change the direction of the comparison operator):

for (int i = 0; i < data.length-1; i++) {
    if (data[i] < data[i+1]) {
        return false;
    }
}
return true;

In both cases, you have to break out of the loop as soon as you find a single pair of numbers that do not hold the ascending-or-descending property, and only return true after the loop exits.

Comments