Rearrange sorted array such that all odd indices elements comes before all even indices element | Java program for the above approach ; 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 thr maximum element ; Driver Code
import java . io . * ; class GFG { static void printTheArray ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } static void rearrange ( int arr [ ] , int N ) { if ( ( N & 1 ) != 0 ) N -- ; int odd_idx = 1 , even_idx = 0 ; int i , max_elem = arr [ N - 1 ] + 1 ; for ( i = 0 ; i < N / 2 ; i ++ ) { arr [ i ] += ( arr [ odd_idx ] % max_elem ) * max_elem ; odd_idx += 2 ; } for ( ; i < N ; i ++ ) { arr [ i ] += ( arr [ even_idx ] % max_elem ) * max_elem ; even_idx += 2 ; } for ( i = 0 ; i < N ; i ++ ) { arr [ i ] = arr [ i ] / max_elem ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 16 , 18 , 19 } ; int N = arr . length ; rearrange ( arr , N ) ; printTheArray ( arr , N ) ; } }