Introduction
Check Sorted Array means:
- verifying whether array elements
- are arranged in increasing order
A sorted array satisfies:
arr[i] <= arr[i+1] Example:
Input: 1 2 3 4 5
Output:True
Explanation:
Every element is smaller than or equal to the next element.This problem is one of the most important applications of:
Recursion on Arrays Constraints
1 <= Array Size <= 10^5 Approach 1 : Iterative Solution
Explanations:
Explanation:
The idea is:
- compare adjacent elements
- verify sorted order
Steps:
- Traverse array.
- Compare current and next element.
- If incorrect order found:
return false. - Otherwise array is sorted.
This approach:
- is simple
- avoids recursion
Dry Run
Array:
1 2 3 4 5
Compare:
1 <= 2
Compare:
2 <= 3
Compare:
3 <= 4
Compare:
4 <= 5Array is sorted.
Practice :
Complexity Analysis :
Time Complexity:- O(n)Explanation :Array is traversed once.
Space Complexity:- O(1) Explanation :
No extra space is used.
Approach 2 : Recursive Solution
Explanations:
Explanation:
This is the most important recursion-based solution.
The idea is:
- compare current element
- with next element
- recursively check remaining array
Base Case:
- when index reaches end
Recursive Case:
- check current pair
- recurse for next index
Dry Run
Array:
1 2 3 4 5
Check:
1 <= 2
Check:
2 <= 3
Check:
3 <= 4
Check:
4 <= 5
Reached end.Array is sorted.
Practice :
Complexity Analysis :