Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to sort array elements using Insertion Sort algorithm in Java ?

Program to demonstrate how to sort array elements using Insertion Sort algorithm in Java

public class InsertionSort {

   public static void main(String[] args) {

      int[] a = {10,3,4,7,1,9,6};
      int nElems = a.length;

      System.out.println("Before Insertion Sort: ");
      for(int k = 0 ; k < a.length; k++)
  System.out.print(a[k] + " ");

      int in, out;
      for(out=1; out < nElems; out++) 
  {
     int temp = a[out]; 
     in = out; 
     while(in > 0 && a[in-1] >= temp) 
     {
  a[in] = a[in-1]; 
  --in; 
     }
     a[in] = temp;

  }

      System.out.println("");
      System.out.println("After Insertion Sort: ");

      for(int i =0; i < a.length; i++){

   System.out.print(a[i] + " ");
      }
   }

}
Output of the program : 

 
 
© 2021 Learn Java by Examples Template by Hubberspot