Check array in descending order

I am writing code to check if my array is in ascending or descending order. If the logical "increase" is true, then I check to see if it rises. If it is incorrect, I check that there is a descent. I need help to check if the array is going down or not ... I have code for checking 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 } } 
+4
source share
3 answers

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

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

Conversely, a downward check should be (and note that this is 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 must exit the loop as soon as you find one pair of numbers that do not contain the property of increasing or decreasing, and return true after the loop exits.

+12
source

You can trick and do it in one cycle, if you want, and remove one add-on:

 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 @OscarLopez code, so I will upgrade it if you reproach mine.

+3
source

To check if ArrayList<Integer> in descending order, try the following:

 boolean isSorted(ArrayList<Integer> list){ boolean sorted = true; for (int i = 1; i < list.size(); i++) { if (list.get(i-1) >= (list.get(i)) ) { sorted = true; } else { return false; } // if else ends } // for "i" ends return sorted; } 
0
source

Source: https://habr.com/ru/post/1494842/


All Articles