Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

java - 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
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...