If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To check if an array is sorted in ascending or descending order, you need to compare each element of the array with its adjacent element. If all elements are in the desired order (either increasing or decreasing), the array is considered sorted.
Here's a Java method to check if an array of integers is sorted in ascending order:
javaCopy code
public class ArraySortChecker {
public static boolean isSortedAscending(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int[] ascendingArray = {1, 2, 3, 4, 5};
int[] descendingArray = {5, 4, 3, 2, 1};
System.out.println("Is ascendingArray sorted? " + isSortedAscending(ascendingArray)); // Output: true
System.out.println("Is descendingArray sorted? " + isSortedAscending(descendingArray)); // Output: false
}
}
In this example, we have a method isSortedAscending
that takes an integer array arr
as an argument. The method uses a loop to compare each element of the array with its adjacent element (i.e., arr[i]
with arr[i+1]
). If any element is greater than its adjacent element, the array is not sorted in ascending order, and the method returns false
. If the loop finishes without finding any out-of-order elements, the array is considered sorted, and the method returns true
.
Similarly, you can create a method to check if an array is sorted in descending order by changing the condition in the loop to arr[i] < arr[i+1]
.
Keep in mind that this method assumes that the array is sorted in strict ascending or descending order. If the array contains duplicate elements and you want to consider it sorted even with duplicate values, you can modify the comparison operator in the loop condition.
Comments: 0