Insertion Sort by Swapping Elements | Utility function to print a Vector ; Function to perform Insertion Sort recursively ; General Case Sort V till second last element and then insert last element into V ; Insertion step ; Insert V [ i ] into list 0. . i - 1 ; Swap V [ j ] and V [ j - 1 ] ; Decrement j ; Driver Code
function printVector ( V ) { for ( let e of V ) { document . write ( e + " " ) ; } document . write ( " " ) ; } function insertionSortRecursive ( V , N ) { if ( N <= 1 ) return ; insertionSortRecursive ( V , N - 1 ) ; let j = N - 1 ; while ( j > 0 && V [ j ] < V [ j - 1 ] ) { let temp = V [ j ] ; V [ j ] = V [ j - 1 ] ; V [ j - 1 ] = temp ; j -= 1 ; } } let A = [ 9 , 8 , 7 , 5 , 2 , 1 , 2 , 3 ] ; document . write ( " " ) ; printVector ( A ) ; document . write ( " " ) ; insertionSortRecursive ( A , A . length ) ; printVector ( A ) ;