Rearrange array such that even index elements are smaller and odd index elements are greater | Rearrange ; function to print array ; Driver Code
let rearrange = ( arr , n ) => { for ( let i = 0 ; i < n - 1 ; i ++ ) { if ( i % 2 == 0 && arr [ i ] > arr [ i + 1 ] ) { let temp = arr [ i ] ; arr [ i ] = arr [ i + 1 ] ; arr [ i + 1 ] = temp ; } if ( i % 2 != 0 && arr [ i ] < arr [ i + 1 ] ) { let temp = arr [ i ] ; arr [ i ] = arr [ i + 1 ] ; arr [ i + 1 ] = temp ; } } } let printArray = ( arr , size ) => { ans = ' ' ; for ( let i = 0 ; i < size ; i ++ ) { ans += arr [ i ] + " " ; } document . write ( ans ) ; } let arr = [ 6 , 4 , 2 , 1 , 8 , 3 ] ; let n = arr . length ; document . write ( " " ) ; printArray ( arr , n ) ; rearrange ( arr , n ) ; document . write ( " " ) ; document . write ( " " ) ; printArray ( arr , n ) ;