Check If Array is Sorted

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 48:-  Check If Array is Sorted

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.

8. Array

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?