Checking an array is sorted in either order efficiently Here is my code, it works fine, just wondering if there any anything to make it even better.

   public static boolean isSorted(int[] arr)
   {
      int n = arr.length;
      int i = 0;
      while (arr[i] == arr[i + 1])  //  same elements at the beginning
         i++;

      if (arr[i] &lt; arr[i + 1])      //  candidate for ascending, non-decreasing
      {
         i++;

         for (; i &lt; n - 1; i++)
         {
            if (arr[i] &gt; arr[i + 1])
               return false;
         }

         return true;
      }

      else                          //  candidate for descending, non-increasing
      {
         i++;

         for (; i &lt; n - 1; i++)
         {
            if (arr[i] &lt; arr[i + 1])
               return false;
         }

         return true;
      }
   }


It works fine, I have just avoided any class or other method.
We could make it better by making it more maintainable by simplifying the code and reducing duplication in the three for-loops. The problem is essentially checking that all successive pairs in the array are either equal or have the same sort order, so let's code it that way:

import static java.lang.Integer.compare;
import static java.lang.Integer.signum;

public static boolean isSorted(final int[] arr) {
    // The order in which the array is.
    // -1: ascending
    //  0: all elements are the same
    //  1: descending
    int arrayOrder = 0;

    for (int i = 0; i &lt; arr.length - 1; i++) {
        // Signum is actually useless, since compare returns -1..1 but
        // we believe the documentation, not the code.
        final int pairOrder = signum(compare(arr[i], arr[i + 1]));

        if (arrayOrder == 0) {
            // All elements so far have been equal. First non-equal pair
            // defines the order expected from the following pairs..
            arrayOrder = pairOrder;
        } else if (pairOrder != arrayOrder &amp;&amp; pairOrder != 0) {
            // If any pair is not equal and deviates from array order,
            // the array is not sorted.
            return false;
        }
    }

    return true;
}


Is this more efficient? No. There are more operations inside the for-loop, but we're talking about two equals checks between integers in an O(N) algorithm. If yours takes 4.7s on my laptop, mine takes 5.4s... for 2^31-1 elements.

A benefit in a single for-loop is that we don't need to expose the loop counter outside the loop itself. Code becomes harder to follow and more error prone when the loop counter is modified outside it's logical scope.