Insertion sort to sort even and odd positioned elements in different orders | C ++ 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
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE 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 ( temp >= arr [ j ] && j >= 0 ) { arr [ j + 2 ] = arr [ j ] ; j -= 2 ; } arr [ j + 2 ] = temp ; } else { while ( temp <= arr [ j ] && j >= 0 ) { arr [ j + 2 ] = arr [ j ] ; j -= 2 ; } arr [ j + 2 ] = temp ; } } } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; printf ( " STRNEWLINE " ) ; } int main ( ) { int arr [ ] = { 12 , 11 , 13 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; evenOddInsertionSort ( arr , n ) ; printArray ( arr , n ) ; return 0 ; }