Positive elements at even and negative at odd positions ( Relative order not maintained ) | Javascript program to rearrange positive and negative numbers ; Move forward the positive pointer till negative number number not encountered ; Move forward the negative pointer till positive number number not encountered ; Swap array elements to fix their position . ; Break from the while loop when any index exceeds the size of the array ; Driver code
function rearrange ( a , size ) { let positive = 0 ; let negative = 1 ; let temp ; while ( true ) { while ( positive < size && a [ positive ] >= 0 ) positive += 2 ; while ( negative < size && a [ negative ] <= 0 ) negative += 2 ; if ( positive < size && negative < size ) { temp = a [ positive ] ; a [ positive ] = a [ negative ] ; a [ negative ] = temp ; } else break ; } } let arr = [ 1 , - 3 , 5 , 6 , - 3 , 6 , 7 , - 4 , 9 , 10 ] ; let n = arr . length ; rearrange ( arr , n ) ; for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ;