Sunday, 29 April 2012

Insertion Sort in Java

import java.io.*;

class InsertionSort 
{
 public static void main(String[] args) 
 {
  try
  {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   System.out.print("Enter name of the source file: ");
   FileReader fr =new FileReader(br.readLine());

   char[] buffer = new char[2048];
   int len = fr.read(buffer);

   String data = new String(buffer,0,len);

   String[] element = data.split(",");

   int[] a = new int[element.length];


   System.out.println("\n\nBefore Sorting: ");

   for(int i=0; i<a.length; i++)
   {
    a[i] = Integer.parseInt(element[i]);
    System.out.println(a[i]);
   }

   int c=0,m=0; //variables to keep track of comparisons and moves


   //Main logic of insertion sort
   for(int i=1; i<a.length; i++)
   {
    for(int j=0;j<i; j++)
    {
     c++;
     if(a[j]>a[i])
     {
      int temp = a[i];
      for(int k=i; k>j; k--)
      {
       a[k] = a[k-1];
       m++;
      }
      
      a[j] = temp;
      m++;      
      break;
     }
    }
   }

   
   System.out.println("\n\nAfter Sorting: ");

   for(int i=0; i<a.length; i++)
   {   
    System.out.println(a[i]);
   }

   System.out.println("\nComparisons = " + c + "\tMoves = " + m);
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
 }
}

No comments:

Post a Comment

Your comments are very much valuable for us. Thanks for giving your precious time.