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 ; Driven code
def countDe ( arr , n ) : NEW_LINE INDENT i = 0 NEW_LINE v = arr . copy ( ) NEW_LINE arr . sort ( ) NEW_LINE count1 = 0 NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( arr [ i ] != v [ i ] ) : NEW_LINE INDENT count1 = count1 + 1 NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT arr . sort ( reverse = True ) NEW_LINE count2 = 0 NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( arr [ i ] != v [ i ] ) : NEW_LINE INDENT count2 = count2 + 1 NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT return ( min ( count1 , count2 ) ) NEW_LINE DEDENT arr = [ 5 , 9 , 21 , 17 , 13 ] NEW_LINE n = 5 NEW_LINE print ( " Minimum ▁ Dearrangement ▁ = " , countDe ( arr , n ) ) NEW_LINE