Skip to content

Instantly share code, notes, and snippets.

@SirPhemmiey
Created August 28, 2019 12:01
Show Gist options
  • Save SirPhemmiey/7f7d94625f32d3b8cd0a5b1841b10e67 to your computer and use it in GitHub Desktop.
Save SirPhemmiey/7f7d94625f32d3b8cd0a5b1841b10e67 to your computer and use it in GitHub Desktop.
function minimumSwaps(arr) {
const visited = arr.slice(0).fill(false)
let swaps = 0;
for (let i = 0; i < arr.length; i++) {
const start = i;
let cycleFound = false;
let current = i;
let cycleLength = 0;
if (visited[current] === false) {
visited[i] = true;
while (!cycleFound) {
visited[current] = true;
current = arr[current] - 1;
if (current === start) {
cycleFound = true;
}
cycleLength++;
}
swaps += (cycleLength - 1);
cycleLength = 0;
}
}
return swaps;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment