Insertion Sort by Swapping Elements | Recursive Java program to sort an array by swapping elements ; Utility function to print a Vector ; Function performs insertion sort on vector V ; 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 by 1 ; Driver code
import java . io . * ; import java . util . * ; class GFG { static void printVector ( Vector < Integer > V ) { for ( int i = 0 ; i < V . size ( ) ; i ++ ) { System . out . print ( V . get ( i ) + " ▁ " ) ; } System . out . println ( ) ; } static void insertionSortRecursive ( Vector < Integer > V , int N ) { if ( N <= 1 ) return ; insertionSortRecursive ( V , N - 1 ) ; int j = N - 1 ; while ( j > 0 && V . get ( j ) < V . get ( j - 1 ) ) { int temp = V . get ( j ) ; V . set ( j , V . get ( j - 1 ) ) ; V . set ( j - 1 , temp ) ; j -= 1 ; } } public static void main ( String [ ] args ) { Vector < Integer > A = new Vector < Integer > ( ) ; A . add ( 0 , 9 ) ; A . add ( 1 , 8 ) ; A . add ( 2 , 7 ) ; A . add ( 3 , 5 ) ; A . add ( 4 , 2 ) ; A . add ( 5 , 1 ) ; A . add ( 6 , 2 ) ; A . add ( 7 , 3 ) ; System . out . print ( " Array : ▁ " ) ; printVector ( A ) ; System . out . print ( " After ▁ Sorting ▁ : " ) ; insertionSortRecursive ( A , A . size ( ) ) ; printVector ( A ) ; } }