Object is to order ascending an unordered list of consecutive integers 1,2,3.....n by swapping numbers (say swapping values at indices 3 and 6), and find the minimum number of swaps needed. My code works, but times out (10 second limit) when given the edge case 100000 integers. How can I streamline this code? To me it feels fairly minimal already - no nested loops or anything. I'm not very experienced with efficiency evaluation, any help would be appreciated, thanks.
function minimumSwaps(arr) {
var swaps = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] !== i+1) {
var tempIndex = arr.indexOf(i+1);
var tempVal = arr[i];
arr[i] = i+1;
arr[tempIndex] = tempVal;
swaps += 1;
}
}
//console.log(swaps)
return swaps;
}