Sunday, December 29, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Program to Check an Array is Sorted or Not

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:

  • Using the Brute Force Approach
  • Using the every() Method
  • Using sort() Method
  • Using Recursion Method

Approach 1: Using the Brute Force Approach

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:

Javascript




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)

Approach 2: Using the every() Method

This is also a kind of iterative method but in this approach we use every() Method for iteration instead of for loop. JavaScript has many inbuilt methods. The Javascript Array.every() method considers all the elements of an array and then further checks whether all the elements of the array satisfy the given condition (passed by in user) or not that is provided by a method passed to it as the argument.

Example:

Javascript




function checkSorted(arr) {
    return arr.every((value, index, array) => 
                     index === 0 || value >= array[index - 1]);
}
// 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(nlogn) 
Auxiliary Space: O(1)

Approach 3: Using sort() Method

This is also very simple method but it is not optimised approach. In this method, we sort the array by using the JavaScript sort() inbuilt method and then compares with the original array that both array are equal or not. If they are equal, then array is sorted.

Example:

Javascript




function checkSorted(arr) {
    const sortArr = [...arr].sort((a, b) => a - b);
    return JSON.stringify(arr) === JSON.stringify(sortArr);
  
}
  
// 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(nlogn) 
Auxiliary Space: O(n)

Approach 4: Using Recursion

  • If we reach the end of the array then it is sorted, this is the base case for recursion.
  • Now, check if the current element is greater than the next element then return false.
  • Otherwise, call the recursive function for next pair of element.

Example:

Javascript




function checkSorted(arr, i = 0) {
    //base case
    if (i === arr.length - 1) {
        return true;
    }
    if (arr[i] > arr[i + 1]) {
        return false;
    }
  
    // Recursive case
    return checkSorted(arr, i + 1);
}
// 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
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments