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

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay