Skip to content

Instantly share code, notes, and snippets.

@gabrielagrandat
Last active August 11, 2020 23:17
Show Gist options
  • Save gabrielagrandat/cef0126783b0a527abc4f293797bc302 to your computer and use it in GitHub Desktop.
Save gabrielagrandat/cef0126783b0a527abc4f293797bc302 to your computer and use it in GitHub Desktop.
Minimum Swaps - HackerRank You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. You need to find the minimum number of swaps required to sort the array in ascending order.
package minimunSwaps;
import java.util.HashMap;
import java.util.Map.Entry;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = { 7, 1, 3, 2, 4, 5, 6 };
System.out.println(minimumSwaps(arr));
}
static int minimumSwaps(int[] arr) {
boolean[] visitedFlag=new boolean[arr.length+1];
int count=0;
HashMap<Integer, Integer> mapItemIndex=new HashMap<>();
for (int i = 1; i <= arr.length; i++) {
mapItemIndex.put(i, arr[i-1]);
}
for (int i = 1; i <= mapItemIndex.size(); i++) { // index = i
int newValue;
if (!visitedFlag[i]) {
visitedFlag[i]=true;
if (mapItemIndex.get(i)!=i) {
int c = mapItemIndex.get(i);
while (!visitedFlag[c]) {
visitedFlag[c]=true;
newValue = mapItemIndex.get(c);
c=newValue;
count++;
}
}
}
}
return count;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment