text: Minimum swaps to make two arrays identical | Java program to make an array same to another using minimum number of swap ; Function returns the minimum number of swaps required to sort the array This method is taken from below post www . geeksforgeeks . org / minimum - number - swaps - required - sort - array / https : ; Create an array of pairs where first element is array element and second element is position of first element ; Sort the array by array element values to get right position of every element as second element of pair . ; To keep track of visited elements . Initialize all elements as not visited or false . ; Initialize result ; Traverse array elements ; already swapped and corrected or already present at correct pos ; find out the number of node in this cycle and add in ans ; move to next node ; Update answer by adding current cycle . ; Return result ; method returns minimum number of swap to make array B same as array A ; map to store position of elements in array B we basically store element to index mapping . ; now we 're storing position of array A elements  in array B. ; returing minimum swap for sorting in modified array B as final answer ; Driver code
code: import java . io . * ; import java . util . * ; class GFG { static int minSwapsToSort ( int arr [ ] , int n ) { ArrayList < ArrayList < Integer > > arrPos = new ArrayList < ArrayList < Integer > > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { arrPos . add ( new ArrayList < Integer > ( Arrays . asList ( arr [ i ] , i ) ) ) ; } Collections . sort ( arrPos , new Comparator < ArrayList < Integer > > ( ) { @ Override public int compare ( ArrayList < Integer > o1 , ArrayList < Integer > o2 ) { return o1 . get ( 0 ) . compareTo ( o2 . get ( 0 ) ) ; } } ) ; boolean [ ] vis = new boolean [ n ] ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( vis [ i ] || arrPos . get ( i ) . get ( 1 ) == i ) continue ; int cycle_size = 0 ; int j = i ; while ( ! vis [ j ] ) { vis [ j ] = true ; j = arrPos . get ( j ) . get ( 1 ) ; cycle_size ++ ; } ans += ( cycle_size - 1 ) ; } return ans ; } static int minSwapToMakeArraySame ( int a [ ] , int b [ ] , int n ) { Map < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { mp . put ( b [ i ] , i ) ; } for ( int i = 0 ; i < n ; i ++ ) b [ i ] = mp . get ( a [ i ] ) ; return minSwapsToSort ( b , n ) ; } public static void main ( String [ ] args ) { int a [ ] = { 3 , 6 , 4 , 8 } ; int b [ ] = { 4 , 6 , 8 , 3 } ; int n = a . length ; System . out . println ( minSwapToMakeArraySame ( a , b , n ) ) ; } }