Rearrange sorted array such that all odd indices elements comes before all even indices element | Function to print the array ; Function to rearrange the array such that odd indexed elements come before even indexed elements ; Reduces the size of array by one because last element does not need to be changed in case N = odd ; Initialize the variables ; Iterate over the range ; Add the modified element at the odd position ; Iterate over the range ; Add the modified element at the even position ; Iterate over the range ; Divide by thr maximum element ; Driver Code
function printTheArray ( arr , N ) { for ( let i = 0 ; i < N ; i ++ ) document . write ( Math . floor ( arr [ i ] ) + " " ) ; } function rearrange ( arr , N ) { if ( N & 1 ) N -- ; let odd_idx = 1 , even_idx = 0 ; let i , max_elem = arr [ N - 1 ] + 1 ; for ( i = 0 ; i < N / 2 ; i ++ ) { arr [ i ] += ( arr [ odd_idx ] % max_elem ) * max_elem ; odd_idx += 2 ; } for ( ; i < N ; i ++ ) { arr [ i ] += ( arr [ even_idx ] % max_elem ) * max_elem ; even_idx += 2 ; } for ( let i = 0 ; i < N ; i ++ ) { arr [ i ] = arr [ i ] / max_elem ; } } let arr = [ 1 , 2 , 3 , 4 , 5 , 16 , 18 , 19 ] ; let N = arr . length ; rearrange ( arr , N ) ; printTheArray ( arr , N ) ;