Minimum number of adjacent swaps for arranging similar elements together | Function to find minimum swaps ; visited array to check if value is seen already ; If the arr [ i ] is seen first time ; stores the number of swaps required to find the correct position of current element 's partner ; Increment count only if the current element has not been visited yet ( if is visited , means it has already been placed at its correct position ) ; If current element 's partner is found ; driver code
function findMinimumAdjacentSwaps ( arr , N ) { let visited = Array ( N + 1 ) . fill ( false ) ; let minimumSwaps = 0 ; for ( let i = 0 ; i < 2 * N ; i ++ ) { if ( visited [ arr [ i ] ] == false ) { visited [ arr [ i ] ] = true ; let count = 0 ; for ( let j = i + 1 ; j < 2 * N ; j ++ ) { if ( visited [ arr [ j ] ] == false ) count ++ ; else if ( arr [ i ] == arr [ j ] ) minimumSwaps += count ; } } } return minimumSwaps ; } let arr = [ 1 , 2 , 3 , 3 , 1 , 2 ] ; let N = arr . length ; N = Math . floor ( N / 2 ) ; document . write ( findMinimumAdjacentSwaps ( arr , N ) ) ;