number of swaps to sort javascript code example
Example 1: swap numbers in javascript
let a = 1;
let b = 2;
let temp;
temp = a;a = b;b = temp;
a; // => 2
b; // => 1
Example 2: minimum number of swaps to sort an array javascript
function minimumSwaps(arr) {
let swap = 0
for(let i = 0;i<arr.length;i++) {
while(arr[i] !== i+1) {
let temp = arr[i]
arr[i] = arr[temp - 1]
arr[temp - 1] = temp
swap++;
}
}
return swap
}