Home > database >  How to check if an integer array is sorted without using an "if" statement?
How to check if an integer array is sorted without using an "if" statement?

Time:11-11

How do I change this code to work without using an if statement? I tried using a while loop and it wasn't working. I've since realised I was using the while loop incorrectly. How do I do it then? (Using java)

public class isSorted {
    public static void main(String[] args) {
        //declaring array literal
        double a[] = {1.5, 4.3, 7.0, 19.5, 25.1, 46.2};
        int L = a.length;
        boolean isSorted = false;
        for (double i = 0; i < L; i  ) {
            if (a[(int) i] < a[(int) (i   1)]) {
                isSorted = true;

            }
            break;
        }
        System.out.println(isSorted);
    }

}

CodePudding user response:

One way to do it is like this:

double a[] = {1.5, 4.3, 7.0, 19.5, 25.1, 46.2};
int i = 0;
while (i < a.length - 1 && a[i] <= a[i   1]) 
    i  ;

boolean isSorted = i >= a.length - 1; 
System.out.println(isSorted);

Basically you check if the current element is less than or equal the next element until you find a mismatch or the whole array is parsed. then checking the value of the i variable will tell you if the array is sorted or not.

For checking descending order just change the condition to:

a[i - 1] >= a[i]
  • Related