Checking if an array is sorted in ascending or descending order.
Here’s an example of a Java program that checks if an array is sorted in ascending or descending order:
public class ArraySortingCheck { public static boolean isAscending(int[] arr) { for (int i = 1; i < arr.length; i++) { if (arr[i] < arr[i - 1]) { return false; } } return true; } public static boolean isDescending(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[] ascendingArray = {1, 2, 3, 4, 5}; int[] descendingArray = {5, 4, 3, 2, 1}; int[] unsortedArray = {2, 1, 3, 5, 4}; System.out.println("Ascending Check:"); System.out.println("Is ascendingArray sorted? " + isAscending(ascendingArray)); System.out.println("Is descendingArray sorted? " + isAscending(descendingArray)); System.out.println("Is unsortedArray sorted? " + isAscending(unsortedArray)); System.out.println("\nDescending Check:"); System.out.println("Is ascendingArray sorted? " + isDescending(ascendingArray)); System.out.println("Is descendingArray sorted? " + isDescending(descendingArray)); System.out.println("Is unsortedArray sorted? " + isDescending(unsortedArray)); } }
In this program, we define two helper methods `isAscending` and `isDescending` to check if the array is sorted in ascending or descending order, respectively.
The `isAscending` method compares each element of the array with the previous element. If it finds any element that is smaller than the previous one, it returns `false`, indicating that the array is not sorted in ascending order. If the loop completes without finding any such element, it returns `true`, indicating that the array is sorted in ascending order.
The `isDescending` method works similarly but checks if each element is greater than the previous one, returning `false` if it finds any element that violates the descending order.
In the `main` method, we test these methods using three arrays: `ascendingArray`, `descendingArray`, and `unsortedArray`. The program prints whether each array is sorted in ascending or descending order.
When you run the program, the output will be:
Ascending Check:
Is ascendingArray sorted? true
Is descendingArray sorted? false
Is unsortedArray sorted? false
Descending Check:
Is ascendingArray sorted? false
Is descendingArray sorted? true
Is unsortedArray sorted? false
“`
As you can see, the program correctly identifies whether each array is sorted in ascending or descending order.