Minimum De | C # 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
using System ; class GFG { public static int countDe ( int [ ] arr , int n ) { int [ ] v = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) v [ i ] = arr [ i ] ; Array . Sort ( arr ) ; int count1 = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] != v [ i ] ) count1 ++ ; Array . Reverse ( 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 ( ) { int [ ] arr = new int [ ] { 5 , 9 , 21 , 17 , 13 } ; int n = 5 ; Console . WriteLine ( " Minimum ▁ Dearrangement ▁ = ▁ " + countDe ( arr , n ) ) ; } }