text: 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 to test above methods
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int minSwapsToSort ( int arr [ ] , int n ) { pair < int , int > arrPos [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { arrPos [ i ] . first = arr [ i ] ; arrPos [ i ] . second = i ; } sort ( arrPos , arrPos + n ) ; vector < bool > vis ( n , false ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( vis [ i ] arrPos [ i ] . second == i ) continue ; int cycle_size = 0 ; int j = i ; while ( ! vis [ j ] ) { vis [ j ] = 1 ; j = arrPos [ j ] . second ; cycle_size ++ ; } ans += ( cycle_size - 1 ) ; } return ans ; } int minSwapToMakeArraySame ( int a [ ] , int b [ ] , int n ) { map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) mp [ b [ i ] ] = i ; for ( int i = 0 ; i < n ; i ++ ) b [ i ] = mp [ a [ i ] ] ; return minSwapsToSort ( b , n ) ; } int main ( ) { int a [ ] = { 3 , 6 , 4 , 8 } ; int b [ ] = { 4 , 6 , 8 , 3 } ; int n = sizeof ( a ) / sizeof ( int ) ; cout << minSwapToMakeArraySame ( a , b , n ) ; return 0 ; }