Pin It

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 : 

 
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot