Rearrange array by interchanging positions of even and odd elements in the given array | Function to replace each even element by odd and vice - versa in a given array ; Stores length of array ; Traverse array ; If current element is even then swap it with odd ; Perform Swap ; Change the sign ; If current element is odd then swap it with even ; Perform Swap ; Change the sign ; Marked element positive ; Prlet final array ; Given array arr [ ] ; Function Call
function replace ( arr ) { let n = arr . length ; for ( let i = 0 ; i < n ; i ++ ) { for ( let j = i + 1 ; j < n ; j ++ ) { if ( arr [ i ] >= 0 && arr [ j ] >= 0 && arr [ i ] % 2 == 0 && arr [ j ] % 2 != 0 ) { let tmp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = tmp ; arr [ j ] = - arr [ j ] ; break ; } else if ( arr [ i ] >= 0 && arr [ j ] >= 0 && arr [ i ] % 2 != 0 && arr [ j ] % 2 == 0 ) { let tmp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = tmp ; arr [ j ] = - arr [ j ] ; break ; } } } for ( let i = 0 ; i < n ; i ++ ) arr [ i ] = Math . abs ( arr [ i ] ) ; for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; } let arr = [ 1 , 3 , 2 , 4 ] ; replace ( arr ) ;