Minimum number of swaps required to sort an array | C ++ program to find minimum number of swaps required to sort an array ; Function returns the minimum number of swaps required to sort the array ; 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 ; Driver program to test the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSwaps ( 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 ++ ; } if ( cycle_size > 0 ) { ans += ( cycle_size - 1 ) ; } } return ans ; } int main ( ) { int arr [ ] = { 1 , 5 , 4 , 3 , 2 } ; int n = ( sizeof ( arr ) / sizeof ( int ) ) ; cout << minSwaps ( arr , n ) ; return 0 ; }