Check whether an array is sorted in Java

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

 

1. Naive

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

Output:

true

 


 

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

 

Download   Run Code

Output:

true

 

2. Apache Commons ArrayUtils

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

 

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of