Insertion sort to sort even and odd positioned elements in different orders | Java program to sort even positioned elements in ascending order and odd positioned elements in descending order . ; Function to calculate the given problem . ; checking for odd positioned . ; Inserting even positioned elements in ascending order . ; sorting the even positioned . ; Inserting odd positioned elements in descending order . ; A utility function to print an array of size n ; Driver program to test insertion sort
class GFG { static void evenOddInsertionSort ( int arr [ ] , int n ) { for ( int i = 2 ; i < n ; i ++ ) { int j = i - 2 ; int temp = arr [ i ] ; if ( ( ( i + 1 ) & 1 ) == 1 ) { while ( j >= 0 && temp >= arr [ j ] ) { arr [ j + 2 ] = arr [ j ] ; j -= 2 ; } arr [ j + 2 ] = temp ; } else { while ( j >= 0 && temp <= arr [ j ] ) { arr [ j + 2 ] = arr [ j ] ; j -= 2 ; } arr [ j + 2 ] = temp ; } } } static void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { System . out . printf ( " % d ▁ " , arr [ i ] ) ; } System . out . printf ( "NEW_LINE"); } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 11 , 13 , 5 , 6 } ; int n = arr . length ; evenOddInsertionSort ( arr , n ) ; printArray ( arr , n ) ; } }