Insertion sort to sort even and odd positioned elements in different orders | 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 code
function evenOddInsertionSort ( arr , n ) { for ( let i = 2 ; i < n ; i ++ ) { let j = i - 2 ; let 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 ; } } } function printArray ( arr , n ) { for ( let i = 0 ; i < n ; i ++ ) { document . write ( arr [ i ] + " " ) ; } document . write ( ) ; } let arr = [ 12 , 11 , 13 , 5 , 6 ] ; let n = arr . length ; evenOddInsertionSort ( arr , n ) ; printArray ( arr , n ) ;