Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
}
like image 902
dmetal23 Avatar asked Dec 06 '22 06:12

dmetal23


2 Answers

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.

like image 90
Óscar López Avatar answered Jan 12 '23 09:01

Óscar López


You can cheat and do it in one loop if you like and remove one addition:

protected boolean isSorted(boolean ascending) {
    for (int i = 1; i < data.length; i++) {
        if (data[i-1] == data[i]) {
            continue;
        }
        if ((data[i-1] > data[i]) == ascending) {
            return false;
        }
    }
    return true;
}

NOTE: I am building on the code by @OscarLopez so upvote his if you upvote mine.

like image 31
Lee Meador Avatar answered Jan 12 '23 09:01

Lee Meador