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.
functioncountSwap(arr,sortedArr){letswapCount=0constvisited=[]for(leti=0;i<arr.length;i++){if(arr[i]===sortedArr[i][0]){visited[i]=truecontinue}letpCount=0;// permutationsletj=i;while(!visited[j]){pCount++visited[j]=truej=sortedArr[j][1]}if(pCount>1)swapCount+=pCount-1// this math based on Permutation Cycle Decomposition}returnswapCount}functionlilysHomework(arr){// Write your code hereconstpArr=arr.map((e,i)=>[e,i])// add position to arrconstaSorted=mergeSort(pArr,true)// ascending sorting, you can choose any sort algoconstdSorted=mergeSort(pArr,false)// descending sortingletaSwapCount=countSwap(arr,aSorted)letdSwapCount=countSwap(arr,dSorted)returnMath.min(aSwapCount,dSwapCount)}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Lily's Homework
You are viewing a single comment's thread. Return to all comments →
Js solution, hope this helps!