Rearrange array such that even index elements are smaller and odd index elements are greater | C # code to rearrange an array such that even index elements are smaller and odd index elements are greater than their next . ; Rearrange ; Utility that prints out an array in a line ; Driver code
using System ; class GFG { static void rearrange ( int [ ] arr , int n ) { int temp ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( i % 2 == 0 && arr [ i ] > arr [ i + 1 ] ) { temp = arr [ i ] ; arr [ i ] = arr [ i + 1 ] ; arr [ i + 1 ] = temp ; } if ( i % 2 != 0 && arr [ i ] < arr [ i + 1 ] ) { temp = arr [ i ] ; arr [ i ] = arr [ i + 1 ] ; arr [ i + 1 ] = temp ; } } } static void printArray ( int [ ] arr , int size ) { for ( int i = 0 ; i < size ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; Console . WriteLine ( ) ; } public static void Main ( ) { int [ ] arr = { 6 , 4 , 2 , 1 , 8 , 3 } ; int n = arr . Length ; Console . WriteLine ( " Before ▁ rearranging : ▁ " ) ; printArray ( arr , n ) ; rearrange ( arr , n ) ; Console . WriteLine ( " After ▁ rearranging : ▁ " ) ; printArray ( arr , n ) ; } }