Minimum De | 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
function countDe ( arr , n ) { let v = [ ] ; for ( let i = 0 ; i < n ; i ++ ) v [ i ] = arr [ i ] ; arr . sort ( ) ; let count1 = 0 ; for ( let i = 0 ; i < n ; i ++ ) if ( arr [ i ] != v [ i ] ) count1 ++ ; arr . reverse ( ) ; let count2 = 0 ; for ( let i = 0 ; i < n ; i ++ ) if ( arr [ i ] != v [ i ] ) count2 ++ ; return ( Math . min ( count1 , count2 ) ) ; } let arr = [ 5 , 9 , 21 , 17 , 13 ] ; let n = 5 ; document . write ( " " + countDe ( arr , n ) ) ;