Rearrange Odd and Even values in Alternate Fashion in Ascending Order | C # implementation of the above approach ; Collection . sort ( ) sorts the collection in ascending order ; ArrayList v1 = new ArrayList ( ) ; to insert even values ArrayList v2 = new ArrayList ( ) ; 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
using System ; using System . Collections ; class GFG { static void AlternateRearrange ( int [ ] arr , int n ) { Array . Sort ( arr ) ; for ( int j = 0 ; j < n ; j ++ ) if ( arr [ j ] % 2 == 0 ) v1 . Add ( arr [ j ] ) ; else v2 . Add ( arr [ j ] ) ; int index = 0 , i = 0 , k = 0 ; bool flag = false ; if ( arr [ 0 ] % 2 == 0 ) flag = true ; while ( index < n ) { if ( flag == true ) { arr [ index ] = ( int ) v1 [ i ] ; i += 1 ; index += 1 ; flag = ! flag ; } else { arr [ index ] = ( int ) v2 [ k ] ; k += 1 ; index += 1 ; flag = ! flag ; } } for ( i = 0 ; i < n ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } static void Main ( ) { int [ ] arr = { 9 , 8 , 13 , 2 , 19 , 14 } ; int n = arr . Length ; AlternateRearrange ( arr , n ) ; } }