DEV Community

Ganesh K S
Ganesh K S

Posted on

Check array is sorted or not

This is my given array

const arr=[1,2,6,4,5]
Enter fullscreen mode Exit fullscreen mode
  • You need traverse through array from the index 1

  • In each loop check the current element (arr[i]) with previous element

  • if current element is greater than previous element then continue with loop else break the loop over there

In the first loop

current element is greater than previous element so you can continue with the loop

Image description

In the second loop

current element is greater than previous element so you can continue with the loop

Image description

In the third loop

current element is lesser than previous element so break the loop

Image description

Solution to check array is sorted or not in javascript

let checkSort = true

for(let i=1;i<arr.length;i++){
  if(arr[i] < arr[i-1]]){
    checkSort=false;
    break;
  }
}

if(checkSort){
  console.log("Array is Sorted")
}else{
  console.log("Array is not sorted)
}
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs