I wrote this code in java in order to do the minimal swaps,
Since the second list is guaranteed to be sorted we can look up for each element in it and find its index from the first list then do a swap between the current indexed element and the one that we found.
Update: I modified findLastElementIndex as it checks if the swapped element will be in the right index after swapping based on list2.
public class Testing {
private static String[] unorderedList = {"Z", "C", "A", "B", "A", "K"};
private static String[] orderedList = {"A", "A", "B", "C", "K", "Z"};
private static int numberOfSwaps;
public static void main(String[] args) {
for (int i = 0; i < unorderedList.length; i++) {
if (!unorderedList[i].equals(orderedList[i])) {
int index = findElementToSwapIndex(i, orderedList[i]);
swapElements(unorderedList, i, index);
}
}
System.out.println(numberOfSwaps);
}
private static void swapElements(String[] list, int indexOfFirstElement, int IndexOfSecElement) {
String temp = list[indexOfFirstElement];
list[indexOfFirstElement] = list[IndexOfSecElement];
list[IndexOfSecElement] = temp;
numberOfSwaps++;
}
private static int findElementToSwapIndex(int currentIndexOfUnorderedList , String letter) {
int lastElementToSwapIndex = 0;
for (int i = 0; i < unorderedList.length; i++) {
if (unorderedList[i].equals(letter)) {
lastElementToSwapIndex = i;
if(unorderedList[currentIndexOfUnorderedList].equals(orderedList[lastElementToSwapIndex])){// check if the swapped element will be in the right place in regard to list 2
return lastElementToSwapIndex;
}
}
}
return lastElementToSwapIndex;
}
}
min number of swaps for this code was the same as in https://stackoverflow.com/a/40507589/6726632
Hopefully this can help you.