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:
- Initialize a variable
sortedtoTrue. - Iterate through the array from the second element to the last.
- For each element, compare it with its previous one.
- If any pair of adjacent elements is in descending order, set
sortedtoFalseand break out of the loop. - After the loop, check the value of
sorted. If it's stillTrue, 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
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;
}