Insertion Sort by Swapping Elements | Recursive CPP 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 Code
#include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; using Vector = vector < int > ; void printVector ( const Vector & V ) { for ( auto e : V ) { cout << e << " ▁ " ; } cout << endl ; } void insertionSortRecursive ( Vector & V , int N ) { if ( N <= 1 ) return ; insertionSortRecursive ( V , N - 1 ) ; int j = N - 1 ; while ( j > 0 and V [ j ] < V [ j - 1 ] ) { swap ( V [ j ] , V [ j - 1 ] ) ; j -= 1 ; } } int main ( ) { Vector A = { 9 , 8 , 7 , 5 , 2 , 1 , 2 , 3 } ; cout << " Array : ▁ " << endl ; printVector ( A ) ; cout << " After ▁ Sorting ▁ : " << endl ; insertionSortRecursive ( A , A . size ( ) ) ; printVector ( A ) ; return 0 ; }