human
Give me a code to rearrange positive and negative numbers with constant extra space and the other steps required given the following:
Rearrange positive and negative numbers with constant extra space | Function to print an array.
Function to reverse an array . An array can be reversed in O ( n ) time and O ( 1 ) space ..
Merges two subarrays of arr [ ] . First subarray is arr [ l . . m ] Second subarray is arr [ m + 1. . r ].
Initial index of 1 st subarray.
Initial index of IInd.
arr [ i . . m ] is positive.
arr [ j . . r ] is positive reverse positive part of left sub - array ( arr [ i . . m ] ).
reverse negative part of right sub - array ( arr [ m + 1. . j - 1 ] ).
reverse arr [ i . . j - 1 ].
Function to Rearrange positive and negative numbers in a array.
Same as ( l + r ) / 2 , but avoids overflow for large l and h.
Sort first and second halves.
Driver Code"
How can the above be solved in Python?
assistant
#Here is code to rearrange positive and negative numbers with constant extra space and the other steps required.
 def printArray ( A , size ) :
	for i in range ( 0 , size ) :
		print ( A [ i ] , end = " ▁ " )
	print ( )
def reverse ( arr , l , r ) :
	if l < r :
		arr [ l ] , arr [ r ] = arr [ r ] , arr [ l ]
		l , r = l + 1 , r - 1
		reverse ( arr , l , r )
def merge ( arr , l , m , r ) :
	i = l
	j = m + 1
	while i <= m and arr [ i ] < 0 :
		i += 1
	while j <= r and arr [ j ] < 0 :
		j += 1
	reverse ( arr , i , m )
	reverse ( arr , m + 1 , j - 1 )
	reverse ( arr , i , j - 1 )
def RearrangePosNeg ( arr , l , r ) :
	if l < r :
		m = l + ( r - l ) // 2
		RearrangePosNeg ( arr , l , m )
		RearrangePosNeg ( arr , m + 1 , r )
		merge ( arr , l , m , r )
if __name__ == " _ _ main _ _ " :
	arr = [ - 12 , 11 , - 13 , - 5 , 6 , - 7 , 5 , - 3 , - 6 ]
	arr_size = len ( arr )
	RearrangePosNeg ( arr , 0 , arr_size - 1 )
	printArray ( arr , arr_size )