How to Check if an Array Is Sorted or Not in Java
Checking whether an array is sorted is a common operation in Java programming. Many algorithms, such as Binary Search, require the input array to be sorted before they work correctly. Verifying the order of an array beforehand helps prevent incorrect results and unnecessary debugging.
The simplest solution is to compare every pair of adjacent elements in a single pass. This tutorial also covers checking for descending order, using Java Streams, and understanding how duplicate values affect the definition of a sorted array.
Problem Statement
Given the following arrays:
int[] numbers1 = {1, 2, 3, 4, 5};
int[] numbers2 = {1, 3, 2, 4};
Determine whether each array is sorted in ascending order.
Output
numbers1 → Sorted
numbers2 → Not Sorted
Method 1: Single Loop with Adjacent Comparison (Ascending Order)
The simplest and most efficient approach is to compare each element with the one immediately before it.
Example
public class Main {
public static boolean isSortedAscending(int[] arr) {
for (int i = 1; i < arr.length; i++) {
if (arr[i] < arr[i - 1]) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(isSortedAscending(numbers));
}
}
Output
true
Explanation
The algorithm compares each element with its previous element.
If any element is smaller than its predecessor, the array is not sorted.
Otherwise, the array is sorted.
Time Complexity: O(n)
Space Complexity: O(1)
Method 2: Check Descending Order
The same logic can be used for descending order by reversing the comparison.
Example
public class Main {
public static boolean isSortedDescending(int[] arr) {
for (int i = 1; i < arr.length; i++) {
if (arr[i] > arr[i - 1]) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int[] numbers = {9, 7, 5, 3, 1};
System.out.println(isSortedDescending(numbers));
}
}
Output
true
Explanation
If any element is greater than the previous element, descending order is violated.
Otherwise, the array is sorted in descending order.
Time Complexity: O(n)
Space Complexity: O(1)
Method 3: Using Java Streams
Java Streams provide a concise way to perform the same check.
Example
import java.util.stream.IntStream;
public class Main {
public static boolean isSortedAscending(int[] arr) {
return IntStream.range(0, arr.length - 1)
.allMatch(i -> arr[i] <= arr[i + 1]);
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(isSortedAscending(numbers));
}
}
Output
true
Explanation
IntStream.range() generates every valid index.
allMatch() verifies that every adjacent pair satisfies the required condition.
Like the loop approach, it stops immediately when a violation is found.
Time Complexity: O(n)
Space Complexity: O(1)
Handling Duplicates Correctly
Consider the following array:
int[] numbers = {1, 2, 2, 3};
Should it be considered sorted?
Most applications answer Yes.
This is called non-decreasing order, where duplicate values are allowed.
The following condition correctly handles duplicates:
if (arr[i] < arr[i - 1])
Only a decrease makes the array unsorted.
If you need strictly increasing order, use:
if (arr[i] <= arr[i - 1])
This rejects duplicate values.
Step-by-Step Explanation
Consider the array:
[1, 3, 2, 4]
Step 1
Compare:
3 and 1
Since:
3 ≥ 1
Continue.
Step 2
Compare:
2 and 3
Since:
2 < 3
The array is no longer sorted.
Return:
false
The algorithm stops immediately.
No further comparisons are necessary.
Internal Working
For the array:
[1, 3, 2, 4]
Comparisons:
1 ≤ 3 ✅
3 ≤ 2 ❌
The second comparison fails.
The method immediately returns:
false
This early termination makes the algorithm efficient in practice.
Real-Life Analogy
Imagine checking whether students are standing in order from the shortest to the tallest.
Walk through the line and compare each student with the person immediately before them.
The moment you find someone shorter than the previous student, you know the line is not correctly arranged.
There is no need to inspect the remaining students.
Best Practices
- Use a single-pass adjacent comparison for maximum efficiency.
- Allow duplicates unless the problem explicitly requires strictly increasing order.
- Test empty arrays and single-element arrays.
- Verify sortedness before performing Binary Search on unknown input.
- Take advantage of early return instead of checking the entire array unnecessarily.
Common Mistakes
1. Rejecting Duplicate Values
Using:
arr[i] <= arr[i - 1]
rejects arrays containing duplicate values.
Use:
arr[i] < arr[i - 1]
when duplicates should be allowed.
2. Continuing After Finding a Violation
Once an incorrect pair is found, immediately return false.
Continuing the loop wastes time.
3. Ignoring Edge Cases
Empty arrays and single-element arrays are considered sorted.
Always test these cases.
4. Mixing Up Ascending and Descending Logic
Ensure the comparison operator matches the required ordering.
Expert Tips
- Checking whether an array is sorted is a common validation step before applying Binary Search.
- Understand the difference between non-decreasing and strictly increasing order.
- Early termination often makes this algorithm much faster than its worst-case complexity suggests.
- The same adjacent-comparison technique can be applied to strings, floating-point values, and custom objects using comparators.
Comparison Table
| Method | Best Case | Worst Case | Allows Duplicates? |
|---|---|---|---|
Single Loop (< Check) |
O(1) | O(n) | ✅ Yes |
Single Loop (<= Check) |
O(1) | O(n) | ❌ No |
Java Streams (allMatch) |
O(1) | O(n) | ✅ Yes (Using <= in the stream condition) |
Frequently Asked Questions
1. What is the time complexity of checking whether an array is sorted?
The worst-case time complexity is O(n) because every adjacent pair may need to be checked. In the best case, the algorithm returns early after the first violation.
2. Are duplicate values allowed in a sorted array?
Yes. Most definitions of a sorted array use non-decreasing order, which allows duplicate values.
3. Is an empty array considered sorted?
Yes. Since there are no elements that violate the ordering, an empty array is considered sorted.
4. How can I check descending order?
Reverse the comparison:
if (arr[i] > arr[i - 1])
Any increase violates descending order.
5. Why should I verify sorting before Binary Search?
Binary Search assumes the array is sorted. Running it on an unsorted array produces unreliable results.
6. Can I use Java Streams to check whether an array is sorted?
Yes. IntStream.range() combined with allMatch() provides a concise and readable solution.
7. What is the difference between sorted and strictly increasing?
A sorted (non-decreasing) array allows duplicate values.
A strictly increasing array requires every element to be greater than the previous one.
8. How can I check whether every row of a 2D array is sorted?
Iterate through each row and apply the same adjacent-comparison logic independently to every row.