Insertion Sort


The insertion sort algorithm is given on the right. It is a sorting algorithm in which the elements are transferred one at a time to the right position. In other words, an insertion sort helps in building the final sorted list, one item at a time, with the movement of higher-ranked elements.
i = 1
while i < length( A )
  x = A[i]
  j = i - 1
  while ( j >= 0 and A[j] > x )
    A[j+1] = A[j]
    j      = j - 1
  end while
  A[j+1] = x
  i      = i + 1
end while

Below is the program implementing the algorithm, where a list of unsorted integers is sent through the command-line arguments, args.

InsertionSort.java (insertion sort)

 // Java program for insertion sort
 public class InsertionSort {
   // Driver method
   public static void main( String args[ ] ) {
     Integer array[ ] = new Integer[ args.length ];
     for ( int i = 0; i < args.length; i++ )
       array[i] = Integer.parseInt( args[i] );
     InsertionSort ob = new InsertionSort( );
     ob.sort( array );
     printArray( array );
   }

   // Method to sort array using insertion sort
   void sort( Integer arr[ ] ) {
     int n = arr.length;
     for ( int i = 1; i < n; ++i ) {
       int key = arr[i];
       int j   = i - 1;
       /* Move elements of arr[0..i-1], that are greater than
          key, to one position ahead of their current position. */
       while ( j >= 0 && arr[j] >  ) {
         arr[j+1] = arr[j];
         j        = j - 1;
       }
       arr[j+1] = ;
     }
   }

   // A utility method to print array of size n
   static void printArray( Integer arr[ ] ) {
     int n = arr.length;
     for ( int i = 0; i < n; ++i )
       System.out.print( arr[i] + " " );
     System.out.println( );
   }
 }
Integers to be sorted:            




      I threw a boomerang a few years ago.    
      I now live in constant fear.