Insertion Sort by Swapping Elements | Iterative Java program to sort an array 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
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 insertionSort ( Vector < Integer > V ) { int N = V . size ( ) ; int i , j , key ; for ( i = 1 ; i < N ; i ++ ) { j = i ; 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 ▁ : " ) ; insertionSort ( A ) ; printVector ( A ) ; } }