Checking if an array is sorted is a basic and commonly asked question in Java interviews. In this post, we’ll check if an array is sorted in ascending or descending order using simple logic.
🧠Approach
We iterate through the array and compare each element with the next one:
- If all elements follow the order:
arr[i] <= arr[i+1]
, then it's ascending. - If all elements follow:
arr[i] >= arr[i+1]
, then it's descending. - Otherwise, it's unsorted.
✅ Java Program
public class CheckArraySorted {
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9};
if (isSortedAscending(arr)) {
System.out.println("Array is sorted in ascending order.");
} else if (isSortedDescending(arr)) {
System.out.println("Array is sorted in descending order.");
} else {
System.out.println("Array is not sorted.");
}
}
static boolean isSortedAscending(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
return false;
}
}
return true;
}
static boolean isSortedDescending(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] < arr[i + 1]) {
return false;
}
}
return true;
}
}
✅ Output
Array is sorted in ascending order.
💡 Tip
This program can be modified to work with float, double, or even String arrays using appropriate comparison logic.
📌 Conclusion
We learned how to check if an array is sorted in Java without using any built-in methods. This is useful in many scenarios like optimization, binary search, or validating input data.