Lily's Homework

  • + 0 comments

    Js solution, hope this helps!

    function countSwap(arr, sortedArr) {
        let swapCount = 0
        const visited = []
        for (let i = 0; i < arr.length; i++) {
            if (arr[i] === sortedArr[i][0]) {
                visited[i] = true
                continue
            }
            let pCount = 0; // permutations
            let j = i;
            while(!visited[j]) {
                pCount ++
                visited[j] = true
                j = sortedArr[j][1]
            }
            if (pCount > 1) swapCount += pCount - 1  // this math based on Permutation Cycle Decomposition
        }
        
        return swapCount
    }
    function lilysHomework(arr) {
        // Write your code here
        const pArr = arr.map((e, i) => [e, i]) // add position to arr
        const aSorted = mergeSort(pArr, true) // ascending sorting, you can choose any sort algo
        const dSorted = mergeSort(pArr, false) // descending sorting
        
        let aSwapCount = countSwap(arr, aSorted)
        let dSwapCount = countSwap(arr, dSorted)
        
        return Math.min(aSwapCount, dSwapCount)
    }