Rearrange Odd and Even values in Alternate Fashion in Ascending Order | Java implementation of the above approach ; Collection . sort ( ) sorts the collection in ascending order ; Vector v1 = new Vector ( ) ; to insert even values Vector v2 = new Vector ( ) ; 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
import java . util . * ; class GFG { static void AlternateRearrange ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] % 2 == 0 ) v1 . add ( arr [ i ] ) ; else v2 . add ( arr [ i ] ) ; int index = 0 , i = 0 , j = 0 ; boolean flag = false ; if ( arr [ 0 ] % 2 == 0 ) flag = true ; while ( index < n ) { if ( flag == true ) { arr [ index ] = ( int ) v1 . get ( i ) ; i += 1 ; index += 1 ; flag = ! flag ; } else { arr [ index ] = ( int ) v2 . get ( j ) ; j += 1 ; index += 1 ; flag = ! flag ; } } for ( i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 9 , 8 , 13 , 2 , 19 , 14 } ; int n = arr . length ; AlternateRearrange ( arr , n ) ; } }