Rearrange positive and negative numbers with constant extra space | A utility function to print an array of size n ; Function to Rearrange positive and negative numbers in a array ; if current element is positive do nothing ; if current element is negative , shift positive elements of arr [ 0. . i - 1 ] , to one position to their right ; Put negative element at its right position ; Driver Code
function printArray ( arr , n ) { for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; document . write ( " " ) ; } function RearrangePosNeg ( arr , n ) { let key , j ; for ( let i = 1 ; i < n ; i ++ ) { key = arr [ i ] ; if ( key > 0 ) continue ; j = i - 1 ; while ( j >= 0 && arr [ j ] > 0 ) { arr [ j + 1 ] = arr [ j ] ; j = j - 1 ; } arr [ j + 1 ] = key ; } } let arr = [ - 12 , 11 , - 13 , - 5 , 6 , - 7 , 5 , - 3 , - 6 ] ; let n = arr . length ; RearrangePosNeg ( arr , n ) ; printArray ( arr , n ) ;