We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Yeah, at first when I didnt notice that the array has to start from 1 and consecutive from there I was confuse too, since it mean we need a sorted array first to even check how many swap we will need in the end. Your 3rd step is basically a sort by itself, and if we have to sort anyway we can skip the whole normalize thing by doing this (in JS)
varorigArray=arr.slice(0);// to keep a copy of the original arrayvarsortedArray=arr.sort();for(vari=0;i<origArray.length;i++){if(origArray[i]!=sortedArray[i]){for(varj=i+1;j<origArray.length;j++){if(origArray[j]===origArray[i]){swap(origArray[i],origArray[j]numberOfSwap++break;}}}}
This way we dont have to worry about normalization at all since we know exactly where each value should be after the mandatory sort either way.
Minimum Swaps 2
You are viewing a single comment's thread. Return to all comments →
Yeah, at first when I didnt notice that the array has to start from 1 and consecutive from there I was confuse too, since it mean we need a sorted array first to even check how many swap we will need in the end. Your 3rd step is basically a sort by itself, and if we have to sort anyway we can skip the whole normalize thing by doing this (in JS)
This way we dont have to worry about normalization at all since we know exactly where each value should be after the mandatory sort either way.