Created
December 1, 2018 22:41
-
-
Save AndrewSouthpaw/eb11fa9670c168d900e1eb515ef66689 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const minimumSwaps = (arr) => { | |
const shift = Math.min(...arr) | |
let swaps = 0 | |
const visited = [...Array(arr.length)].map(() => false) | |
arr.forEach((val, i) => { | |
if (val - shift === i || visited[i]) return | |
let loopLength = 0 | |
let x = i | |
while (!visited[x]) { | |
visited[x] = true | |
x = arr[x] - shift | |
loopLength++ | |
} | |
swaps += loopLength - 1 | |
}) | |
return swaps | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment