Minimum number of swaps required to sort an array | Java program to find minimum number of swaps required to sort an array ; swap function ; indexOf function ; Return the minimum number of swaps required to sort the array ; This is checking whether the current element is at the right place or not ; Swap the current element with the right index so that arr [ 0 ] to arr [ i ] is sorted ; Driver class ; Driver program to test the above function ; Output will be 5
import java . util . * ; import java . io . * ; class GfG { public void swap ( int [ ] arr , int i , int j ) { int temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; } public int indexOf ( int [ ] arr , int ele ) { for ( int i = 0 ; i < arr . length ; i ++ ) { if ( arr [ i ] == ele ) { return i ; } } return - 1 ; } public int minSwaps ( int [ ] arr , int N ) { int ans = 0 ; int [ ] temp = Arrays . copyOfRange ( arr , 0 , N ) ; Arrays . sort ( temp ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] != temp [ i ] ) { ans ++ ; swap ( arr , i , indexOf ( arr , temp [ i ] ) ) ; } } return ans ; } } class Main { public static void main ( String [ ] args ) throws Exception { int [ ] a = { 101 , 758 , 315 , 730 , 472 , 619 , 460 , 479 } ; int n = a . length ; System . out . println ( new GfG ( ) . minSwaps ( a , n ) ) ; } }