Insertion Sort by Swapping Elements | Utility function to print a Vector ; Function performs insertion sort on vector V ; Insert V [ i ] into list 0. . i - 1 ; Swap V [ j ] and V [ j - 1 ] ; Decrement j by 1 ; Driver Code
function printVector ( V ) { for ( let e of V ) { document . write ( e + " " ) ; } document . write ( " " ) ; } function insertionSort ( V ) { let N = V . length ; let i , j , key ; for ( i = 1 ; i < N ; i ++ ) { j = i ; 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 ( " " + " " ) ; insertionSort ( A ) ; printVector ( A ) ;