Insertion Sort by Swapping Elements | Recursive python program to sort an array 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 method
import math NEW_LINE def printVector ( V ) : NEW_LINE INDENT for i in V : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT print ( " ▁ " ) NEW_LINE DEDENT def insertionSortRecursive ( V , N ) : NEW_LINE INDENT if ( N <= 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT insertionSortRecursive ( V , N - 1 ) NEW_LINE j = N - 1 NEW_LINE while ( j > 0 and V [ j ] < V [ j - 1 ] ) : NEW_LINE INDENT temp = V [ j ] ; NEW_LINE V [ j ] = V [ j - 1 ] ; NEW_LINE V [ j - 1 ] = temp ; NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT A = [ 9 , 8 , 7 , 5 , 2 , 1 , 2 , 3 ] NEW_LINE n = len ( A ) NEW_LINE print ( " Array " ) NEW_LINE printVector ( A ) NEW_LINE print ( " After ▁ Sorting ▁ : " ) NEW_LINE insertionSortRecursive ( A , n ) NEW_LINE printVector ( A ) NEW_LINE