We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
functionmain(){...// Write your code hereletnumberOfSwaps=0for(leti=0;i<n;i++){// Track number of elements swapped during a single array traversalfor(letj=0;j<n-1;j++){// Swap adjacent elements if they are in decreasing orderif(a[j]>a[j+1]){;[a[j],a[j+1]]=[a[j+1],a[j]]numberOfSwaps++}}// If no elements were swapped during a traversal, array is sortedif(numberOfSwaps==0){break}}console.log(`Array is sorted in ${numberOfSwaps} swaps.`)console.log(`First Element: ${a[0]}`)console.log(`Last Element: ${a[a.length-1]}`)}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Day 20: Sorting
You are viewing a single comment's thread. Return to all comments →
In JavaScript