Check whether an array is sorted in Java
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class Main { public static boolean isSorted(int[] a) { // base case if (a == null || a.length <= 1) { return true; } for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } public static void main(String[] args) { int[] a = { 1, 2, 3, 4, 5 }; System.out.println(isSorted(a)); // true } } |
Here’s an equivalent version using the Stream API.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.stream.IntStream; class Main { public static boolean isSorted(int[] a) { // base case if (a == null || a.length <= 1) { return true; } return IntStream.range(0, a.length - 1).noneMatch(i -> a[i] > a[i + 1]); } public static void main(String[] args) { int[] a = { 1, 2, 3, 4, 5 }; System.out.println(isSorted(a)); // true } } |
We can even write a recursive procedure for the same, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class Main { public static boolean isSorted (int[] a, int index) { // base case if (a == null || a.length <= 1 || index == 1) { return true; } if (a[index - 1] < a[index - 2]) { return false; } return isSorted(a, index - 1); } public static void main(String[] args) { int[] a = { 1, 2, 3, 4, 5 }; System.out.println(isSorted(a, a.length)); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import org.apache.commons.lang3.ArrayUtils; class Main { public static boolean isSorted (int[] a) { // works with v3.4 or above return ArrayUtils.isSorted(a); } public static void main(String[] args) { int[] a = { 1, 2, 3, 4, 5 }; System.out.println(isSorted(a)); // true } } |
That’s all about determining whether an array is sorted in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)