Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JavaScript - Check if array is sorted (irrespective of the order of sorting)
In JavaScript, checking if an array is sorted regardless of order (ascending or descending) requires comparing adjacent elements to determine if they follow a consistent pattern. We need to identify whether the array is sorted in ascending order, descending order, or not sorted at all.
Understanding the Problem
An array can be considered sorted if all elements follow either:
- Ascending order: each element is greater than or equal to the previous one
- Descending order: each element is less than or equal to the previous one
Method 1: Check Both Directions
This approach checks if the array is sorted in either ascending or descending order:
const isSorted = (arr) => {
if (arr.length arr[i - 1]) {
isDescending = false;
}
}
return isAscending || isDescending;
};
// Test cases
console.log(isSorted([1, 3, 56, 87, 99])); // Ascending
console.log(isSorted([99, 87, 56, 3, 1])); // Descending
console.log(isSorted([1, 3, 2, 4])); // Not sorted
console.log(isSorted([5, 5, 5])); // Equal elements
true true false true
Method 2: Early Exit Optimization
This optimized version stops checking as soon as it determines the array isn't sorted:
const isSortedOptimized = (arr) => {
if (arr.length arr[i - 1]) {
if (direction === -1) return false; // Was descending, now ascending
direction = 1;
} else if (arr[i]
true
true
false
Edge Cases
Important edge cases to consider:
// Empty array and single element
console.log(isSorted([])); // true
console.log(isSorted([42])); // true
// Arrays with duplicate values
console.log(isSorted([1, 2, 2, 3])); // true (ascending with duplicates)
console.log(isSorted([3, 2, 2, 1])); // true (descending with duplicates)
// All identical elements
console.log(isSorted([7, 7, 7, 7])); // true
true
true
true
true
true
Comparison
| Method | Time Complexity | Space Complexity | Early Exit |
|---|---|---|---|
| Check Both Directions | O(n) | O(1) | No |
| Early Exit Optimization | O(n) best case O(1) | O(1) | Yes |
Conclusion
Use the early exit method for better performance on large arrays. Both approaches handle edge cases like empty arrays, single elements, and duplicate values correctly.
