878245. Check whether the array is sorted or not

Easy

Check whether the array is sorted or not

Summary

Given an array, check if it's sorted in ascending order. This problem involves arrays and sorting concepts.

Detailed Explanation

The approach to solve this problem is straightforward. We simply need to iterate through the array and compare each element with its next one. If all elements are in ascending order, then the array is sorted. Otherwise, it's not.

Here's a step-by-step breakdown of the solution:

  1. Initialize a variable sorted to True.
  2. Iterate through the array from the second element to the last.
  3. For each element, compare it with its previous one.
  4. If any pair of adjacent elements is in descending order, set sorted to False and break out of the loop.
  5. After the loop, check the value of sorted. If it's still True, then the array is sorted.

Time complexity: O(n), where n is the length of the array. Space complexity: O(1), as we only use a constant amount of space to store the sorted variable.

Here's an ASCII art diagram representing the array:

[3, 4, 5, 6, 7]
 ^       ^
|  compare |
----------------

Optimized Solutions

Java

View on GeeksforGeeks
public boolean isSorted(int[] arr) {
    boolean sorted = true;
    for (int i = 1; i < arr.length; i++) {
        if (arr[i - 1] > arr[i]) {
            sorted = false;
            break;
        }
    }
    return sorted;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.