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.
✅ Master Array Traversal & Order Validation in Java
Checking whether an array is sorted is a foundational Java problem often used as a prerequisite for optimized algorithms. Strengthen your understanding of array traversal, comparisons, and edge cases by exploring these related Java programs and interview resources.
๐ง Java Coding Round Questions
Practice array-based logic problems asked in coding rounds.
๐ซ Remove Duplicates from Array
Sorted arrays enable efficient duplicate removal techniques.
๐ Find Duplicates in Array
Learn how sorted arrays simplify duplicate detection.
๐ Reverse Array
Strengthen array traversal and index manipulation skills.
๐ฅ Second Largest Element in Array
Practice scanning arrays while maintaining value constraints.
๐ Sort Array Without Built-ins
Learn sorting algorithms often used before order validation.
๐ฆ Java Collections Interview Questions
Understand ordering concepts in lists, sets, and maps.
๐ฏ Java Interview Questions (Freshers)
Common interview questions involving arrays and sorting.
๐งช Advanced Java Programs (Real-World)
Apply array-order validation in real-world Java problems.