Generate Least Derangement
int [ ] D = new int [ N + 1 ] ; PQ . Sort ( ) ; for ( int i = 1 ; i <= N ; i ++ ) { PQ . Sort ( ) ; int d = PQ [ 0 ] ; PQ . RemoveAt ( 0 ) ; if ( d != S [ i ] i == N ) { D [ i ] = d ; } else { PQ . Sort ( ) ; D [ i ] = PQ [ 0 ] ; PQ . RemoveAt ( 0 ) ; PQ . Add ( d ) ; } } if ( D [ N ] == S [ N ] ) { int t = D [ N - 1 ] ; D [ N - 1 ] = D [ N ] ; D [ N ] = t ; }