Write the definition of a static method named isSorted that receives two arguments: an array of references to objects that implement the Comparable interface and a boolean. If the boolean is true then the method returns true if the objects referenced in the array are in ascending order. On the other hand, if the boolean is false, the method returns true if the objects are in descending order. The method also returns true for arrays of 0 or 1 length. For all other situations, the method returns false.

LANGUAGE: JAVA

CHALLENGE:

Write the definition of a static method named isSorted that receives two arguments: an array of references to objects that implement the Comparable interface and a boolean. If the boolean is true then the method returns true if the objects referenced in the array are in ascending order. On the other hand, if the boolean is false, the method returns true if the objects are in descending order. The method also returns true for arrays of 0 or 1 length. For all other situations, the method returns false.

SOLUTION:

public static boolean isSorted(Comparable[] x, boolean y) {
   boolean isAscending = true;
   if (x.length==0 || x.length==1) return true;
   else if (y){
      for (int i=0; isAscending &amp;&amp; i<x.length-1; i++)
      if (x[i].compareTo(x[i+1]) > 0)
         isAscending = false; // descending
   }else{
      for (int i=0; isAscending && i<x.length-1; i++)
      if (x[i].compareTo(x[i+1]) < 0)
      isAscending = false; // descending
   }

   return isAscending;
}