Rearrange Odd and Even values in Alternate Fashion in Ascending Order | Javascript implementation of the above approach ; Sort the array ; var v1 = [ ] ; to insert even values var v2 = [ ] ; to insert odd values ; Set flag to true if first element is even ; Start rearranging array ; If first element is even ; Else , first element is Odd ; Print the rearranged array ; Driver code
function AlternateRearrange ( arr , n ) { arr . sort ( ( a , b ) => a - b ) ; for ( var i = 0 ; i < n ; i ++ ) if ( arr [ i ] % 2 == 0 ) v1 . push ( arr [ i ] ) ; else v2 . push ( arr [ i ] ) ; var index = 0 , i = 0 , j = 0 ; var flag = false ; if ( arr [ 0 ] % 2 == 0 ) flag = true ; while ( index < n ) { if ( flag == true ) { arr [ index ++ ] = v1 [ i ++ ] ; flag = ! flag ; } else { arr [ index ++ ] = v2 [ j ++ ] ; flag = ! flag ; } } for ( i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; } var arr = [ 9 , 8 , 13 , 2 , 19 , 14 ] ; var n = arr . length ; AlternateRearrange ( arr , n ) ;