Check Array Is Sorted in Java
Problem
An array is sorted in ascending order when every element is less than or equal to the one right after it.
Given an array of integers, determine whether it is sorted in ascending order.
Java Program
public class CheckArrayIsSorted {
public static void main(String[] args) {
int[] arr = {2, 5, 9, 14, 20};
boolean sorted = true;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
sorted = false;
break; // out-of-order pair found, no need to keep checking
}
}
System.out.println("Is sorted: " + sorted);
}
}Output
Core Logic
Comparing every element against the one right after it, and stopping at the first out-of-order pair, confirms whether the whole array is sorted.
- 1
sortedstarts astrue, assuming the array qualifies until proven otherwise. - 2The loop runs from
0toarr.length - 2, comparing each element against its immediate neighbor. - 3
if (arr[i] > arr[i + 1])checks whether a pair is out of order — the current element is bigger than the one that should come after it. - 4The first out-of-order pair found sets
sortedtofalseand exits the loop immediately withbreak.
[2, 5, 9, 14, 20], every adjacent pair increases, so the loop finishes with sorted still true.Key Point: The loop only needs to check adjacent pairs, not every possible pair — if every neighboring pair is in order, the whole array must be in order by transitivity.
Why: Each adjacent pair is checked once, and the loop exits at the first out-of-order pair found, without allocating anything beyond a boolean flag.
Key Concepts
Approach 2: Java 8
import java.util.stream.IntStream;
public class CheckArrayIsSortedStream {
public static void main(String[] args) {
int[] arr = {2, 5, 9, 14, 20};
// allMatch() short-circuits at the first out-of-order pair
boolean sorted = IntStream.range(0, arr.length - 1).allMatch(i -> arr[i] <= arr[i + 1]);
System.out.println("Is sorted: " + sorted);
}
}
Output
Core Logic
The same adjacent-pair check can ask a stream directly — does every element satisfy 'not greater than its neighbor'?
- 1
IntStream.range(0, arr.length - 1)generates every valid index that has a neighbor to its right. - 2
.allMatch(i -> arr[i] <= arr[i + 1])checks that every adjacent pair is in non-decreasing order. - 3
allMatch()returnstrueonly if every pair qualifies, and stops at the first one that doesn't.
[2, 5, 9, 14, 20], allMatch() checks all four adjacent pairs and finds none out of order, so it returns true.Key Point: allMatch() short-circuits the same way the loop's break did — it stops checking as soon as an out-of-order pair is found.
Why: allMatch() stops as soon as it finds an out-of-order pair, the same short-circuiting behavior as the loop's break.