How to use the Brute Force Approach In Javascript
In this approach, we iterate through the array and compare each element with the next one. If the first element is greater than the next element then we return false, else return true.
Example:
function checkSorted(arr) {
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
return false;
}
}
return true;
}
// Example usage
const arr1 = [32, 39, 48, 56];
const arr2 = [22, 65, 1, 39];
console.log(checkSorted(arr1));
console.log(checkSorted(arr2));
Output
true false
Time Complexity: O(n)
Auxiliary Space: O(1)
JavaScript Program to Check an Array is Sorted or Not
In this article, we will learn how to check if the array is sorted in JavaScript. JavaScript Array is a single variable that is used to store elements of different data types. Now, we have to find whether the array is sorted or not.
Examples:
Input : const arr = [1, 2, 3, 4, 5];
Output : true
Input : const arr = [3, 1, 4, 2, 5];
Output : false
Below are the following approaches through which we can check if the array is sorted or not:
Table of Content
- Using the Brute Force Approach
- Using the every() Method
- Using sort() Method
- Using Recursion
- Using Array.reduce()