Tutorialspoint
Problem
Solution
Submissions

Check if Array is Sorted

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a JavaScript program to determine if a given array of integers is sorted in ascending order. An array is considered sorted if each element is less than or equal to the next element. The function should return true if the array is sorted, false otherwise.

Example 1
  • Input: arr = [1, 2, 3, 4, 5]
  • Output: true
  • Explanation:
    • The array [1, 2, 3, 4, 5] is checked element by element.
    • 1 <= 2, 2 <= 3, 3 <= 4, 4 <= 5 - all conditions are satisfied.
    • Therefore, the array is sorted in ascending order.
Example 2
  • Input: arr = [1, 3, 2, 4, 5]
  • Output: false
  • Explanation:
    • The array [1, 3, 2, 4, 5] is checked element by element.
    • 1 <= 3 is true, but 3 <= 2 is false.
    • Since one condition fails, the array is not sorted in ascending order.
Constraints
  • 1 ≤ arr.length ≤ 1000
  • -1000 ≤ arr[i] ≤ 1000
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysTech MahindraLTIMindtree
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Iterate through the array from the first element to the second last element
  • Compare each element with the next element in the array
  • If any element is greater than the next element, return false immediately
  • If the loop completes without finding any violation, return true
  • Handle edge cases like empty arrays or single element arrays

Steps to solve by this approach:

 Step 1: Handle edge cases - if array has 0 or 1 element, it's considered sorted
 Step 2: Initialize a loop from index 0 to array length - 2
 Step 3: Compare current element with the next element
 Step 4: If current element is greater than next element, return false immediately
 Step 5: Continue the loop until all adjacent pairs are checked
 Step 6: If loop completes without violations, return true
 Step 7: Test with various input arrays to verify the solution

Submitted Code :