Minimum De | Java code for counting minimum de - arrangements present in an array . ; function to count Dearrangement ; create a copy of original array ; sort the array ; traverse sorted array for counting mismatches ; reverse the sorted array ; traverse reverse sorted array for counting mismatches ; return minimum mismatch count ; driver code
import java . util . * ; import java . lang . * ; import java . util . Arrays ; public class GeeksforGeeks { public static int countDe ( int arr [ ] , int n ) { int v [ ] = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) v [ i ] = arr [ i ] ; Arrays . sort ( arr ) ; int count1 = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] != v [ i ] ) count1 ++ ; Collections . reverse ( Arrays . asList ( arr ) ) ; int count2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] != v [ i ] ) count2 ++ ; return ( Math . min ( count1 , count2 ) ) ; } public static void main ( String argc [ ] ) { int arr [ ] = { 5 , 9 , 21 , 17 , 13 } ; int n = 5 ; System . out . println ( " Minimum ▁ Dearrangement ▁ = ▁ " + countDe ( arr , n ) ) ; } }