Skip to content

Instantly share code, notes, and snippets.

@AndrewSouthpaw
Created December 1, 2018 22:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewSouthpaw/eb11fa9670c168d900e1eb515ef66689 to your computer and use it in GitHub Desktop.
Save AndrewSouthpaw/eb11fa9670c168d900e1eb515ef66689 to your computer and use it in GitHub Desktop.
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