Minimum swaps to make two arrays identical | C # 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
using System ; using System . Collections . Generic ; using System . Linq ; public class GFG { static int minSwapsToSort ( int [ ] arr , int n ) { List < List < int > > arrPos = new List < List < int > > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { arrPos . Add ( new List < int > ( ) { arr [ i ] , i } ) ; } arrPos = arrPos . OrderBy ( x => x [ 0 ] ) . ToList ( ) ; bool [ ] vis = new bool [ n ] ; Array . Fill ( vis , false ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( vis [ i ] arrPos [ i ] [ 1 ] == i ) continue ; int cycle_size = 0 ; int j = i ; while ( ! vis [ j ] ) { vis [ j ] = true ; j = arrPos [ j ] [ 1 ] ; cycle_size ++ ; } ans += ( cycle_size - 1 ) ; } return ans ; } static int minSwapToMakeArraySame ( int [ ] a , int [ ] b , int n ) { Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { mp . Add ( b [ i ] , i ) ; } for ( int i = 0 ; i < n ; i ++ ) { b [ i ] = mp [ a [ i ] ] ; } return minSwapsToSort ( b , n ) ; } static public void Main ( ) { int [ ] a = { 3 , 6 , 4 , 8 } ; int [ ] b = { 4 , 6 , 8 , 3 } ; int n = a . Length ; Console . WriteLine ( minSwapToMakeArraySame ( a , b , n ) ) ; } }