Rearrange sorted array such that all odd indices elements comes before all even indices element | Function to print the array ; Function to rearrange the array such that odd indexed elements come before even indexed elements ; Reduces the size of array by one because last element does not need to be changed in case N = odd ; Initialize the variables ; Iterate over the range ; Add the modified element at the odd position ; Iterate over the range ; Add the modified element at the even position ; Iterate over the range ; Divide by the maximum element ; 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 rearrange ( arr , N ) : NEW_LINE INDENT if ( N & 1 ) : NEW_LINE INDENT N -= 1 NEW_LINE DEDENT odd_idx = 1 NEW_LINE even_idx = 0 NEW_LINE max_elem = arr [ N - 1 ] + 1 NEW_LINE for i in range ( N // 2 ) : NEW_LINE INDENT arr [ i ] += ( arr [ odd_idx ] % max_elem ) * max_elem NEW_LINE odd_idx += 2 NEW_LINE DEDENT for i in range ( N // 2 , N ) : NEW_LINE INDENT arr [ i ] += ( arr [ even_idx ] % max_elem ) * max_elem NEW_LINE even_idx += 2 NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT arr [ i ] = arr [ i ] // max_elem NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 16 , 18 , 19 ] NEW_LINE N = len ( arr ) NEW_LINE rearrange ( arr , N ) NEW_LINE printArray ( arr , N ) ; NEW_LINE DEDENT