This post will check whether the specified array is sorted according to natural ordering or not in Java. An array is considered not sorted if any successor has a less value than its predecessor.

1. Naive solution

The idea is to loop over the array and compare each element to its successor. Now for any pair of consecutive elements, the array is considered unsorted if the first element is found to be more in value than the second element. The array is considered sorted if we have reached the end of the array.

Download  Run Code

 
Here’s an equivalent version using the Stream API.

Download  Run Code

 
We can even write a recursive procedure for the same, as shown below:

Download  Run Code

2. Using Apache Commons Lang

Another good alternative is to use the Apache Commons Lang library, which offers the static utility method isSorted() in the ArrayUtils class.

Download Code

That’s all about determining whether an array is sorted in Java.