Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...