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.
Could you please elaborate on the swapInPlace method.
Update: Never mind, I think I understood.
Also since I feel theres no need to call the methods and the swap can be done within the for loop I have updated it to a version with everything done within the for loop.
static int minimumSwaps(int[] arr) {
int temp = 0, swaps = 0;
for (int i = 0; i < arr.length;) {
if (arr[i] != i + 1){
// System.out.println("Swapping --"+arr[arr[i] - 1] +" AND -- "+arr[i]);
temp = arr[arr[i] - 1];
arr[arr[i] - 1] = arr[i];
arr[i] = temp;
++swaps;
} else
++i;
// System.out.println("value at position -- "+ i +" is set to -- "+ arr[i]);
}
return swaps;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Minimum Swaps 2
You are viewing a single comment's thread. Return to all comments →
Could you please elaborate on the swapInPlace method.
Update: Never mind, I think I understood. Also since I feel theres no need to call the methods and the swap can be done within the for loop I have updated it to a version with everything done within the for loop.