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
def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def RearrangePosNeg ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT key = arr [ i ] NEW_LINE if ( key > 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT j = i - 1 NEW_LINE while ( j >= 0 and arr [ j ] > 0 ) : NEW_LINE INDENT arr [ j + 1 ] = arr [ j ] NEW_LINE j = j - 1 NEW_LINE DEDENT arr [ j + 1 ] = key NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 12 , 11 , - 13 , - 5 , 6 , - 7 , 5 , - 3 , - 6 ] NEW_LINE n = len ( arr ) NEW_LINE RearrangePosNeg ( arr , n ) NEW_LINE printArray ( arr , n ) NEW_LINE DEDENT