Input: Unordered consecutive integer array e.g. [6,4,3,1,2,5] Output: Minimum number of swaps required to sort the array in ascending order [1,2,3,4,5,6]
For the same purpose the C implementation is:
int minimumSwaps(vector<int> arr) {
int i,c=0,n=arr.size();
for(i=0;i<n;i )
{
if(arr[i]==(i 1))
continue;
swap(arr[i],arr[arr[i]-1]);
c ;
i--;
}
return c;
}
The C code is working fine!!
But when the same logic is implemented in JavaScript it is going into endless loop leading to runtime error.
JavaScript implementation:
function minimumSwaps(arr) {
let swaps=0,n=arr.length,i=0;
for(i=0; i<n; i ){
if(arr[i]===(i 1))
continue;
let temp= arr[i];
arr[i]= arr[arr[i]-1];
arr[arr[i]-1]=temp;
swaps ;
i--;
}
return swaps;
}
How to solve this issue and make the JavaScript code working?
CodePudding user response:
function minimumSwaps(arr) {
let swaps = 0, n = arr.length, i = 0;
for (i = 0; i < n; i ) {
if (arr[i] === (i 1)) {
let temp = arr[i];
arr[i] = arr[arr[i] - 1];
arr[arr[i] - 1] = temp;
swaps ;
}
}
return swaps;
}
CodePudding user response:
Issue with swaping value between array's index. in c you used a method but in js you tried to write manually, but your written code is wrong
Instead use this code, it is optimized
function minimumSwaps(arr) {
let swaps=0,n=arr.length,j=0;
for(var i=0; i<n; i=j){
if(arr[i]!=(i 1)){
var temp = arr[i];
arr[i] = arr[temp-1];
arr[temp-1] = temp;
swaps ;
}else j ;
}
return swaps;
}
Or simply optimize your code
for(i=0; i<n; i ){
if(arr[i]===(i 1))
continue;
let temp= arr[i]; //temp is 6 as per your list
arr[i]= arr[arr[i]-1]; //just now you changed arr[i] into arr[arr[i]-1] , so it will become 5 as per your list,
arr[temp-1]=temp; //now temp-1 is 5 but if you use arr[arr[i]-1] it will become 4 bcoz arr[i] is 5 now
swaps ;
i--;
}
in your code the issue was,
first you set temp
to arr[i]
and arr[i]
to arr[arr[i]-1]
so next time when you call arr[arr[i]-1]
it become arr[arr[arr[i]-1]-1 as you previously set arr[i] as arr[arr[i]-1]