Rearrange Odd and Even values in Alternate Fashion in Ascending Order | Python3 implementation of the above approach ; Sort the array ; v1 = list ( ) to insert even values v2 = list ( ) 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
def AlternateRearrange ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT v1 . append ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT v2 . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT index = 0 NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE flag = False NEW_LINE if ( arr [ 0 ] % 2 == 0 ) : NEW_LINE INDENT flag = True NEW_LINE DEDENT while ( index < n ) : NEW_LINE INDENT if ( flag == True and i < len ( v1 ) ) : NEW_LINE INDENT arr [ index ] = v1 [ i ] NEW_LINE index += 1 NEW_LINE i += 1 NEW_LINE flag = ~ flag NEW_LINE DEDENT elif j < len ( v2 ) : NEW_LINE INDENT arr [ index ] = v2 [ j ] NEW_LINE index += 1 NEW_LINE j += 1 NEW_LINE flag = ~ flag NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 9 , 8 , 13 , 2 , 19 , 14 , 21 , 23 , 25 ] NEW_LINE n = len ( arr ) NEW_LINE AlternateRearrange ( arr , n ) NEW_LINE