text: Minimum number of swaps required to sort an array of first N number | Function to find minimum swaps ; Initialise count variable ; If current element is not at the right position ; Swap current element with correct position of that element ; Increment for next index when current element is at correct position ; Driver code ; Function to find minimum swaps
code: #include <iostream> NEW_LINE using namespace std ; int minimumSwaps ( int arr [ ] , int n ) { int count = 0 ; int i = 0 ; while ( i < n ) { if ( arr [ i ] != i + 1 ) { while ( arr [ i ] != i + 1 ) { int temp = 0 ; temp = arr [ arr [ i ] - 1 ] ; arr [ arr [ i ] - 1 ] = arr [ i ] ; arr [ i ] = temp ; count ++ ; } } i ++ ; } return count ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 1 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimumSwaps ( arr , n ) ; }