Rearrange array such that arr [ i ] >= arr [ j ] if i is even and arr [ i ] <= arr [ j ] if i is odd and j < i | function to rearrange the array ; total even positions ; total odd positions ; copy original array in an auxiliary array ; sort the auxiliary array ; fill up odd position in original array ; fill up even positions in original array ; display array ; Driver code
function rearrangeArr ( arr , n ) { let evenPos = Math . floor ( n / 2 ) ; let oddPos = n - evenPos ; let tempArr = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) tempArr [ i ] = arr [ i ] ; tempArr . sort ( ) ; let j = oddPos - 1 ; for ( let i = 0 ; i < n ; i += 2 ) { arr [ i ] = tempArr [ j ] ; j -- ; } j = oddPos ; for ( let i = 1 ; i < n ; i += 2 ) { arr [ i ] = tempArr [ j ] ; j ++ ; } for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; } let arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] ; let size = arr . length ; rearrangeArr ( arr , size ) ;