Introduction
Checking whether an array is sorted means verifying if the elements are arranged in increasing order.
Given an array of integers arr[] of size n, the task is to determine whether the array is sorted in non-decreasing order.
This is a fundamental array problem that helps in understanding array traversal, adjacent comparisons, and validation techniques.
Example:
Input: arr[] = [1, 2, 3, 4, 5]Output: True Explanation: Each element is smaller than or equal to the next element. Therefore, the array is sorted.
Input: arr[] = [2, 5, 1, 8, 9] Output: False Explanation: 5 is greater than 1. Therefore, the array is not sorted.
Constraints
1 <= n <= 10^5
-10^9 <= arr[i] <= 10^9
Explanation
The simplest way to check whether an array is sorted is:
- Traverse the array
- Compare every element with the next element
- If any element is greater than the next element, the array is not sorted
This approach is simple and easy to understand.
Steps
- Traverse the array from index 0 to n-2.
- Compare current element with next element.
- If current element is greater:
- return False
- If traversal completes successfully:
- return True
Dry Run
Input Array: [1, 2, 3, 4, 5]Compare 1 and 2: 1 <= 2 Array remains sorted Compare 2 and 3: 2 <= 3
Array remains sorted Compare 3 and 4: 3 <= 4 Array remains sorted Compare 4 and 5: 4 <= 5 Array remains sorted No violation found. Final Result: True
Brute Force Code (Python)
Complexity Analysis
Time Complexity: O(n)Explanation: The array is traversed once. Each adjacent pair is checked exactly one time.
Space Complexity: O(1) Explanation: No extra data structures are used. Only a boolean variable is required.
Approach 2 : Optimized Solution
Explanation
The traversal solution itself is already the optimized solution because every adjacent pair may need to be checked once.
Therefore:
- O(n) is the best possible time complexity.
- Constant extra space is sufficient.
This makes the comparison approach both simple and optimal.
Steps
- Traverse the array.
- Compare current element with next element.
- If any element violates sorted order:
- return False
- Otherwise:
- return True
Dry Run
Input Array: [2, 5, 1, 8, 9]Compare 2 and 5:
2 <= 5
Array remains sorted
Compare 5 and 1:
5 > 1
Sorted order is violated
Final Result: FalseOptimized Code